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

Flutter中映射对象列表生成UI报错,求解决方法

Flutter列表映射Column报错解决

问题代码

定义的列表:

const List categories = [
  {'title': 'category 1', 'value': 1000},
  {'title': 'category 2', 'value': 2000},
  {'title': 'category 3', 'value': 3000},
];

渲染用的Column代码:

Column(
  mainAxisAlignment: MainAxisAlignment.start,
  crossAxisAlignment: CrossAxisAlignment.start,
  children: categories.map((e) => Category(title: e.title, value: e.value)).toList(),
),

错误信息

运行时提示:类型“List”不是类型“List”的子类型,同时代码中e.title、e.value的写法错误——列表元素是Map类型,不能通过.访问属性。

解决方案

方案1:修正类型标注与取值方式

  1. 给列表指定明确的Map类型:
const List<Map<String, dynamic>> categories = [
  {'title': 'category 1', 'value': 1000},
  {'title': 'category 2', 'value': 2000},
  {'title': 'category 3', 'value': 3000},
];
  1. 用Map键取值语法替换.,并转换列表类型为List<Widget>:
Column(
  mainAxisAlignment: MainAxisAlignment.start,
  crossAxisAlignment: CrossAxisAlignment.start,
  children: categories.map((e) => Category(title: e['title'], value: e['value'])).toList() as List<Widget>,
),

方案2:创建实体类(推荐)

此方式类型更安全,代码可读性更高:

  1. 定义实体类:
class CategoryModel {
  final String title;
  final int value;

  const CategoryModel({required this.title, required this.value});
}
  1. 重新定义类型明确的列表:
const List<CategoryModel> categories = [
  CategoryModel(title: 'category 1', value: 1000),
  CategoryModel(title: 'category 2', value: 2000),
  CategoryModel(title: 'category 3', value: 3000),
];
  1. 正常映射渲染:
Column(
  mainAxisAlignment: MainAxisAlignment.start,
  crossAxisAlignment: CrossAxisAlignment.start,
  children: categories.map((e) => Category(title: e.title, value: e.value)).toList(),
),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 00:35:26