如何解决Flutter中_CastError:Null不是String子类型的问题
解决JSON转Model的
_CastError问题 错误根源
你碰到的_CastError (type 'Null' is not a subtype of type 'String' in type cast),核心问题是JSON返回的数据里存在null值,但你的Product模型把对应字段强制声明为非空的String类型。late关键字只是延迟变量初始化的时机,根本解决不了JSON里的null数据问题。
从截图代码来看,你大概率是这样写的:
class Product { late final String name; late final String description; Product.fromJson(Map<String, dynamic> json) { name = json['name'] as String; description = json['description'] as String; } }
一旦JSON里的name或description字段是null,用as String强制转换就会触发这个报错。
可行解决方案
1. 允许字段为null(推荐)
如果业务逻辑允许该字段为空,直接把字段类型改成可空的String?:
class Product { final String? name; final String? description; Product.fromJson(Map<String, dynamic> json) : name = json['name'] as String?, description = json['description'] as String?; }
后续使用时记得处理null场景,比如:
Text(product.name ?? '默认名称')
2. 给null字段设置默认值
如果业务上要求字段必须有值,就在解析时给null值赋默认字符串:
class Product { final String name; final String description; Product.fromJson(Map<String, dynamic> json) : name = json['name'] as String? ?? '默认名称', description = json['description'] as String? ?? '默认描述'; }
3. 使用json_serializable库(规范方案)
复杂项目建议用json_serializable自动生成解析代码,能自动处理null情况,避免手动转换出错:
- 先往
pubspec.yaml里加依赖:
dependencies: json_annotation: ^4.8.1 dev_dependencies: build_runner: ^2.4.4 json_serializable: ^6.7.0
- 定义模型并添加注解:
import 'package:json_annotation/json_annotation.dart'; part 'product.g.dart'; @JsonSerializable() class Product { final String? name; final String description; Product({this.name, required this.description}); factory Product.fromJson(Map<String, dynamic> json) => _$ProductFromJson(json); Map<String, dynamic> toJson() => _$ProductToJson(this); }
- 运行命令生成解析代码:
flutter pub run build_runner build
内容的提问来源于stack exchange,提问作者WonderingDino
相关产品推荐
相关产品推荐

