【发布时间】:2018-09-24 18:07:11
【问题描述】:
我在 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',
},],
},]
我通过几个Widgets 传递它,并且在某些时候我想将键值对{'didBuy':false} 添加到成分列表中的每个Map(基本上是recipeList['ingredients'])。
因此我称之为:
List<Map<String, dynamic>> resultList = recipeList['ingredients'].map((elem) {
elem.addAll({'didBuy': false});
print(elem);
}).toList();
很遗憾,出现以下错误消息:Dart Error: Unhandled exception:type '_InternalLinkedHashMap<String, bool>' is not a subtype of type 'Map<String, String>' of 'other'。
有没有人知道在地图上添加东西而不收到此错误消息的正确方法是什么?
将问题编辑得更准确。
编辑2:
按照 Hadrien 的建议,在 Map 内显式调用 List 的类型后,我可以使用布尔值添加键值对。长期想从网上获取数据,所以我定义了一个RecipeObj:
class RecipeObj{
String name;
int id;
String img;
List<Map<String, dynamic>> ingredients;
RecipeObj(this.name, this.id, this.img, this.ingredients);
}
这里我明确说明了成分属性的类型,所以我想我可以得到(主)recipeList 中的显式调用。但是通过一些widget向下传递成分属性后,flutter识别为List<Map<String, String>>,虽然我到处都定义为List<Map<String, dynamic>>,这是为什么呢?
【问题讨论】:
-
什么是
ingredients和recipeList他们应该是一样的吗? -
此代码
recipeList['ingredients'].无效。recipeList是一个列表,而不是映射,您需要使用整数索引访问元素。也许你的意思是recipeList[0]['ingredients'].