【问题标题】:type 'MappedListIterable<dynamic, Widget>' is not a subtype of type 'Widget'类型 'MappedListIterable<dynamic, Widget>' 不是类型 'Widget' 的子类型
【发布时间】: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 编程,所以我对类型的经验有限。

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

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您的_getIngredients 需要一个小部件的返回值。 在每个示例中,您要么返回列表,要么返回地图。

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

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

    这里是这样的:

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

    【讨论】:

    • 嗨,迈克。谢谢,你的建议就像一个魅力。我理解您将返回类型从 Widget 更改为 Widget 列表的意思。我不明白 ... 运算符,所以我需要进一步研究。
    • 在 dart 中称为扩展运算符,这里有一个简单但很好的解释的快速链接:spread operator
    猜你喜欢
    • 2021-03-16
    • 2023-03-27
    • 1970-01-01
    • 2019-08-18
    • 2018-09-11
    • 2020-09-11
    • 2021-05-17
    • 2023-03-27
    相关资源
    最近更新 更多