如何修复Flutter中List<String>不是String子类型的错误?
问题:已声明字段为List类型,仍出现
List<String> is not a subtype of String错误 我在数据模型里已经把部分字段声明为List类型了,但一直碰到List<String> is not a subtype of String的错误,以下是我的代码:
数据模型代码
class DataModel{ String ID; List<String> name; List<String> type; List<String> images; DataModel({ required this.ID, required this.name, required this.type, required this.images, }); factory DataModel.fromJson(Map<String, dynamic> json) { return DataModel( ID: json['ID'] ?? '' , name: json['name'] ?? '' , type: List<String>.from(json['type']??[]) , images: List<String>.from(json['images']??[]) , ); } Map<String, Object> toJsonAdd() => { "ID":ID, "name": name, "images": images, "type": type, }; }
数据传递代码
List<String> nameList =[]; List<String> typeList =[]; List<String> imageList =[]; add(DataModel dataModel) async { await ref.read(dataProvider).addData(dataModel).then((success) {}); } DataModel dataModel = DataModel( ID: '', name: nameList.toList(), type: typeList.toList(), images: imageList.toList(), ); add(dataModel);
错误原因
问题出在fromJson工厂构造函数的name字段赋值逻辑:
name字段声明的类型是List<String>,但当json['name']为null时,你用?? ''给它赋了空字符串(String类型),直接造成类型不匹配,触发报错。- 对比
type和images字段的处理,它们用List<String>.from(json['xxx']??[]),默认值是空数组[],完全符合List类型要求。
修复方案
把name字段的默认值改成空数组,并用List<String>.from()包裹,和type、images保持一致:
修改后的fromJson代码:
factory DataModel.fromJson(Map<String, dynamic> json) { return DataModel( ID: json['ID'] ?? '' , name: List<String>.from(json['name']??[]) , type: List<String>.from(json['type']??[]) , images: List<String>.from(json['images']??[]) , ); }
这样当json['name']为null时,会赋值一个空的List<String>,和字段声明的类型完全匹配,就不会再出现类型转换错误了。
内容的提问来源于stack exchange,提问作者Jabu
相关产品推荐
相关产品推荐

