You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart中如何返回String?等可空类型对应的Type类型实例

Dart可空类型转换实现方案

1. 修改类型映射函数,直接返回对应可空类型

Dart空安全环境下,可直接通过类型?语法获取对应可空类型的Type实例,修改转换函数如下:

Type _jsonTypeToDart(String? type) {
  if (type == null) {
    return dynamic;
  }

  switch (type) {
    case 'string':
      return String;
    case '?string':
      return String?;
    case 'float':
      return double;
    case '?float':
      return double?;
    case 'int':
      return int;
    case '?int':
      return int?;
    case 'json':
      return Map;
    case '?json':
      return Map?;
    case 'bool':
      return bool;
    case '?bool':
      return bool?;
    default:
      return dynamic;
  }
}

2. 调整类型校验与转换逻辑

原有value.runtimeType == type的判断逻辑存在两个缺陷:

  • 可空类型场景下,null的runtimeType为Null,与String?这类可空类型的Type不相等,但null属于合法的可空类型值
  • 无法兼容int转double这类合法的类型转换场景
    因此新增两个辅助方法处理校验和转换逻辑:
// 校验值是否符合目标类型要求
bool _matchType(dynamic value, Type targetType) {
  switch (targetType) {
    case String: return value is String;
    case String?: return value is String || value == null;
    case double: return value is double || value is int;
    case double?: return value is double || value is int || value == null;
    case int: return value is int;
    case int?: return value is int || value == null;
    case bool: return value is bool;
    case bool?: return value is bool || value == null;
    case Map: return value is Map;
    case Map?: return value is Map || value == null;
    default: return true; // dynamic类型直接匹配
  }
}

// 按目标类型执行转换
dynamic _convertByType(dynamic value, Type targetType) {
  if (value == null) return null;
  if (targetType == double || targetType == double?) {
    if (value is int) return value.toDouble();
  }
  // 其他自定义转换规则可在此扩展
  return value;
}

修改后的业务使用逻辑:

dynamic value = setting['value'];
Type targetType = _jsonTypeToDart(setting['type']);
if (_matchType(value, targetType)) {
  return _convertByType(value, targetType);
}
// 此处可添加类型不匹配的异常处理逻辑

内容的提问来源于stack exchange,提问作者vixez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 00:45:02