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(), ),
错误信息
运行时提示:类型“Liste.title、e.value的写法错误——列表元素是Map类型,不能通过.访问属性。
解决方案
方案1:修正类型标注与取值方式
- 给列表指定明确的Map类型:
const List<Map<String, dynamic>> categories = [ {'title': 'category 1', 'value': 1000}, {'title': 'category 2', 'value': 2000}, {'title': 'category 3', 'value': 3000}, ];
- 用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:创建实体类(推荐)
此方式类型更安全,代码可读性更高:
- 定义实体类:
class CategoryModel { final String title; final int value; const CategoryModel({required this.title, required this.value}); }
- 重新定义类型明确的列表:
const List<CategoryModel> categories = [ CategoryModel(title: 'category 1', value: 1000), CategoryModel(title: 'category 2', value: 2000), CategoryModel(title: 'category 3', value: 3000), ];
- 正常映射渲染:
Column( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: categories.map((e) => Category(title: e.title, value: e.value)).toList(), ),
内容的提问来源于stack exchange,提问作者anon
相关产品推荐
相关产品推荐

