类型 'MappedListIterable<dynamic, Widget>' 不是类型 'Widget' 的子类型

Ste*_*ois 0 dart flutter

我正在开发 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']),
  ],
),
Run Code Online (Sandbox Code Playgroud)

_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();    
}
Run Code Online (Sandbox Code Playgroud)

显然,我对类型系统有一些不了解。我也不明白我应该如何找出正确的类型。我理解常规的 Dart 类型没有问题,如 String、int、List、Map 等等,但是 Flutter 类型让我有点失望。我通常用 JS 或 Python 编程,所以我对类型的经验有限。

关于如何解决我的类型问题的任何指示?

小智 5

_getIngredients期望 Widget 的返回值。在你的每个例子中,你要么返回一个列表,要么返回一个地图。

所以我认为你想要的是返回一个像这样的 Widget 列表:

List<Widget> _getIngredients(ingredients) {
  // type 'List<Widget>' is not a subtype of type 'Widget'
  return ingredients.map<Widget>((i) => Text(i['amount'])).toList();    
}
Run Code Online (Sandbox Code Playgroud)

这里是这样的:

Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: [
    Text(
      'Ingredients',
      style: TextStyle(
        fontSize: 20,
        fontWeight: FontWeight.bold,
      ),
    ),
    ..._getIngredients(recipe['ingredients']), // the ... operator adds to array
  ],
),
Run Code Online (Sandbox Code Playgroud)