英文:
How to fix List<String> is not subtype of String error?
问题
你为什么一直收到错误消息List<String>不是String的子类型
,如果在我的模型中已经声明了我要收集某些字段的List<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: List<String>.from(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);
请注意,我修复了一些代码错误,确保DataModel
的构造函数参数与实际使用时的参数匹配,并且dataModel
的变量名与类名一致。
英文:
How do I keep on getting the error List<String> is not a subtype of String
, if in my model I've already declared that I want to collect a List<String> for certain fields within the model?
So, below is code for my data model :
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,
};
}
Now, below is where I'm using the model to pass data to db:
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(),
mealTypes: filteredMealTypes.toList(),
priceOfType: filteredPriceMealType.toList(),
);
add(menuModel);
答案1
得分: 0
我认为你的数据库
无法存储List
类型的String
或任何类型的List
,这就是为什么它一直产生相同错误的原因。
尝试将你的list
转换成String
并存储到数据库
中。
你可以使用类似dart:convert
的东西,它有类似jsonEncode
的方法,将字符串列表传递给它,它将把它转换成字符串。
在检索数据时,你可以再次使用jsonDecode将你的字符串列表转换为dart列表类型。
英文:
I think your database
is not capable of storing List
of String
or any kind of List
at all, that is why it keeps producing same error.
Try to convert your list
in to String
and store it in database
.
You can use something like dart:convert
which has method something like jsonEncode
and pass the list of string to it and it will convert it to string.
Also on retrieving data you can again use jsonDecode to convert you string list to dart list type.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论