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

如何解决Flutter中‘type 'Null' is not a subtype of type 'String' in type cast’错误

解决Flutter中type 'Null' is not a subtype of type 'String' in type cast错误

问题本质

错误是因为DataModel.fromJson方法里,把JSON返回的null值强制转换成了非空String类型。虽然控制台能打印数据库返回的数据,但其中部分记录的Name字段为null,模型解析时未处理该情况,导致类型转换失败。

解决方案

方案1:将模型字段改为可空类型

修改DataModel定义,允许Name为null,同时在UI层处理null显示:

class DataModel {
  final String? Name; // 改为可空String类型

  DataModel({this.Name});

  factory DataModel.fromJson(Map<String, dynamic> json) {
    return DataModel(
      Name: json['Name'] as String?, // 直接接收null值
    );
  }
}

更新UI展示代码,处理null情况:

Text(dataList[index].Name ?? '暂无名称')

方案2:给模型字段设置默认值

如果要求Name必须为非空字符串,解析时将null替换为空字符串或默认值:

class DataModel {
  final String Name; // 保持非空约束

  DataModel({required this.Name});

  factory DataModel.fromJson(Map<String, dynamic> json) {
    return DataModel(
      // 若字段为null则返回空字符串,避免类型转换错误
      Name: json['Name'] as String? ?? '',
    );
  }
}

方案3:过滤含null字段的记录

如果不需要保留Name为null的记录,可在解析前先过滤:

return dataFromDB
    .where((item) => item['Name'] != null) // 过滤Name为null的条目
    .map((e) => DataModel.fromJson(e))
    .toList();

额外排查步骤

  1. 查看print(dataFromDB)的输出,确认是否存在Name字段为null的记录;
  2. 检查数据库对应表的Name字段是否允许为空,若业务上不允许,可在数据库层面设置非空约束,从源头避免null值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 23:02:42