You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从嵌套列表的子列表取数据渲染列表并解决Dart类型不匹配报错

问题根源
  • 你当前遍历的对象是全局breakfastProducts列表,列表内每个元素都是Breakfast类实例,直接将该类型实例传给仅接受String参数的Text组件,就会触发类型不匹配报错
  • 你的BreakfastIngredient组件已经通过构造参数传入了单个Breakfast实例,不需要再调用全局列表,直接取该实例下的ingredients字段遍历即可
  • 代码中声明的late List ingredients变量未被使用,属于冗余内容可直接删除
修正后的代码
class BreakfastIngredient extends StatefulWidget {
  const BreakfastIngredient({
    Key? key,
    required this.breakfast,
  }) : super(key: key);

  final Breakfast breakfast;

  @override
  _BreakfastIngredientState createState() => _BreakfastIngredientState();
}

class _BreakfastIngredientState extends State<BreakfastIngredient> {
  @override
  Widget build (BuildContext context) {
    // 直接取传入的Breakfast实例的ingredients字段遍历
    return Wrap(
      // 用Wrap替换Row避免食材文本过多时横向溢出,需要逐行展示可替换为Column
      children: widget.breakfast.ingredients.map((ingredientStr){
        return Text(ingredientStr);
      }).toList()
    );  
  }
}
补充说明

如果你需要展示全局breakfastProducts中所有早餐的食材列表,需要做两层遍历:先遍历每个Breakfast实例,再遍历每个实例下的ingredients子列表即可。

内容的提问来源于stack exchange,提问作者Gheh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 16:54:10