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

Flutter报错:List<Map<String,Object>>无法强转为目标List类型

错误成因
  • 核心原因是Dart泛型的类型校验严格,你写了两处不符合实际数据结构的类型声明/强转:
    1. 你尝试给_ques声明的类型List<Map<String,List<Map<String,int>>>>完全不符合实际数据结构:每个问题Map中同时存在String类型的questionText字段、List类型的answers字段,Map的value类型并不统一,不可能全部是List<Map<String,int>>,因此这个类型声明本身就不合法,Dart会自动回退到动态类型推导,等于你写的声明没生效。
    2. quiz.dart中你把answers字段强转为List<Map<String, int>>是完全错误的:每个answer的Map里同时存在String类型的text字段、int类型的score字段,Map的value类型是Object,不可能是全int类型,因此运行时强转必然抛出类型不匹配错误。
修复方案

按以下两步修改即可解决问题:

  1. 修正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}
    ]
  },
];
  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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 06:48:15