Flutter报错:List<Map<String,Object>>无法强转为目标List类型
错误成因
- 核心原因是Dart泛型的类型校验严格,你写了两处不符合实际数据结构的类型声明/强转:
- 你尝试给
_ques声明的类型List<Map<String,List<Map<String,int>>>>完全不符合实际数据结构:每个问题Map中同时存在String类型的questionText字段、List类型的answers字段,Map的value类型并不统一,不可能全部是List<Map<String,int>>,因此这个类型声明本身就不合法,Dart会自动回退到动态类型推导,等于你写的声明没生效。 quiz.dart中你把answers字段强转为List<Map<String, int>>是完全错误的:每个answer的Map里同时存在String类型的text字段、int类型的score字段,Map的value类型是Object,不可能是全int类型,因此运行时强转必然抛出类型不匹配错误。
- 你尝试给
修复方案
按以下两步修改即可解决问题:
- 修正
main.dart中_ques的类型声明,匹配真实数据结构:
// 正确的类型声明:外层列表每一项是Map,key为String,value为混合类型Object final List<Map<String, Object>> _ques = const [ { 'questionText': 'What\'s your fav. color?', 'answers': [ {'text': 'Black', 'score': 10}, {'text': 'Red', 'score': 5}, {'text': 'Green', 'score': 3}, {'text': 'White', 'score': 1}, ] }, { 'questionText': 'What\'s your fav. animal?', 'answers': [ {'text': 'Cat', 'score': 5}, {'text': 'Dog', 'score': 3}, {'text': 'Snake', 'score': 4}, {'text': 'Bird', 'score': 2} ] }, { 'questionText': 'Who\'s your fav. instructor?', 'answers': [ {'text': 'Max', 'score': 1}, {'text': 'Max', 'score': 1}, {'text': 'Max', 'score': 1} ] }, ];
- 修正
quiz.dart中的类型强转逻辑,匹配真实的answers数据类型,同时去掉冗余的回调强转:
@override Widget build(BuildContext context) { return Column( children: [ Question( array![questionIndex!]['questionText'] as String, ), // 把answers强转为正确的List<Map<String, Object>>类型,而非错误的int类型 ...((array)![questionIndex!]['answers'] as List<Map<String, Object>>) .map((question) { return Answer( // 取值时再单独做对应类型的转换,去掉多余的VoidCallback强转 () => fun!(question['score'] as int), question['text'] as String ); }).toList(), ], ); }
补充:如果后续要做更健壮的类型校验,建议不要用Map来存结构化数据,直接定义Question、Answer的实体类,能从根源避免这类运行时类型转换错误。
内容的提问来源于stack exchange,提问作者Anand
相关产品推荐
相关产品推荐

