如何从嵌套列表的子列表取数据渲染列表并解决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
相关产品推荐
相关产品推荐

