【发布时间】:2020-09-02 16:57:21
【问题描述】:
我正在开发一个 Flutter 应用程序,我需要在其中迭代地图。
地图的内容如下所示:({amount: 1, ingredient: Egg}, {amount: 2 ss, ingredient: Havremel})(它作为地图数组存储在数据库中。不知道为什么 Dart 会这样输出它,而不是从一个列表开始)。
每当我映射数据时都会遇到类型错误。我在一个单独的函数中分离数据,并从一个列小部件中调用它:
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Ingredients',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
),
),
_getIngredients(recipe['ingredients']),
],
),
_getIngredients 函数。我试图以多种方式输入这个。错误消息在每行的顶部注释。
Widget _getIngredients(ingredients) {
// type 'MappedListIterable<dynamic, Widget>' is not a subtype of type 'Widget'
return ingredients.map<Widget>((i) => Text(i['amount']));
// type 'MappedListIterable<dynamic, dynamic>' is not a subtype of type 'Widget'
return ingredients.map((i) => Text(i['amount']));
// type 'List<dynamic>' is not a subtype of type 'Widget'
return ingredients.map((i) => Text(i['amount'])).toList();
// type 'List<Widget>' is not a subtype of type 'Widget'
return ingredients.map<Widget>((i) => Text(i['amount'])).toList();
}
显然,我对类型系统有些不理解。我也不明白我应该如何找出正确的类型。我理解常规的 Dart 类型没有问题,如 String、int、List、Map 等等,但是 Flutter 类型让我有点失望。我通常用 JS 或 Python 编程,所以我对类型的经验有限。
关于如何解决我的类型问题的任何指示?
【问题讨论】: