我在 Flutter 中得到以下信息List<Map>:
List<Map<String, dynamic>> recipeList = [
{
'name': 'rec1',
'id': 1,
'img': 'images/recipe.jpg',
'ingredients': [{
'name': 'salt',
'amount': '1',
'unit': '1',
},
{
'name': 'flour',
'amount': '100',
'unit': 'g',
},
{
'name': 'water',
'amount': '100',
'unit': 'g',
},
{
'name': 'milk',
'amount': '100',
'unit': 'g',
},],
},]
Run Code Online (Sandbox Code Playgroud)
我将它传递给几个Widgets,在某个时候我想将键值对添加{'didBuy':false}到成分列表中的每个Map(基本上是recipeList['ingredients'])。因此我呼吁:
List<Map<String, dynamic>> resultList = recipeList['ingredients'].map((elem) {
elem.addAll({'didBuy': false});
print(elem);
}).toList();
Run Code Online (Sandbox Code Playgroud)
不幸的是,出现以下错误消息:Dart Error: Unhandled exception:type '_InternalLinkedHashMap<String, bool>' is not a subtype of type 'Map<String, String>' of 'other'。
有谁知道向地图添加内容的正确方法是什么,而不会收到此错误消息?
编辑问题以使其更准确。
ListEDIT2:按照 Hadrien 建议的方式显式调用内部的类型后 Map,我可以添加带有布尔值的键值对。长期来看我想从互联网上获取数据,所以我定义了一个RecipeObj:
class RecipeObj{
String name;
int id;
String img;
List<Map<String, dynamic>> ingredients;
RecipeObj(this.name, this.id, this.img, this.ingredients);
}
Run Code Online (Sandbox Code Playgroud)
在这里,我明确声明了配料属性的类型,因此我认为我可以在(主)recipeList 内进行显式调用。但是在通过一些小部件传递成分属性后,flutter 将其识别为List<Map<String, String>>,尽管我在所有地方都将其定义为List<Map<String, dynamic>>,这是为什么呢?
dart 推断成分列表的类型Map<String, String>
您可以在列表中自己指定类型
'ingredients': <Map<String, dynamic>>[ {
'name': 'salt',
'amount': '1',
'unit': '1',
},
Run Code Online (Sandbox Code Playgroud)
Map<String, dynamic>或者在你的map函数内部构建一个新的
List<Map<String, dynamic>> resultList = recipeList['ingredients'].map((elem) {
final map = Map<String, dynamic>.from(elem);
map.addAll({'didBuy': false});
return map;
}).toList();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8893 次 |
| 最近记录: |