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

Flutter中‘List<String>无法转为String’类型转换错误求助

错误原因与修复方案

错误根源

在results_screen.dart的getSummaryData方法中,你将'question'字段的值赋值为questions[i].answers(这是一个列表类型),但在questions_summary.dart的组件代码里,你尝试把data['question']强制转换成String类型,这直接导致了type 'List' is not a subtype of type 'String' in type cast错误。

修复步骤

  1. 修正数据赋值逻辑
    把getSummaryData里的'question'字段改成题目文本(而非选项列表),假设你的Question类中题目文本的字段名为text,修改后的代码如下:

    List<Map<String, Object>> getSummaryData() {
      final List<Map<String, Object>> summary = [];
    
      for (var i = 0; i < chosenAnswers.length; i++) {
        summary.add({
          'question_index': i,
          'question': questions[i].text, // 替换为题目文本字段
          'correct_answer': questions[i].answers[0],
          'user_answer': chosenAnswers[i]
        });
      }
      return summary;
    }
    
  2. 可选:添加类型安全防护
    为避免后续出现类似类型转换问题,可在QuestionsSummary组件中添加空值兜底:

    Text(data['question'] as String? ?? '未知题目'),
    

模拟数据示例

假设你的questions数据结构如下:

class Question {
  final String text;
  final List<String> answers;

  const Question({required this.text, required this.answers});
}

final List<Question> questions = [
  Question(
    text: 'Flutter是哪个公司开发的?',
    answers: ['Google', 'Apple', 'Microsoft', 'Facebook'],
  ),
  Question(
    text: 'Dart是强类型语言吗?',
    answers: ['是', '否'],
  ),
];

修复后,getSummaryData生成的模拟数据为:

[
  {
    'question_index': 0,
    'question': 'Flutter是哪个公司开发的?',
    'correct_answer': 'Google',
    'user_answer': 'Google'
  },
  {
    'question_index': 1,
    'question': 'Dart是强类型语言吗?',
    'correct_answer': '是',
    'user_answer': '是'
  }
]

此时QuestionsSummary组件就能正常渲染所有字段,不会再出现类型转换错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 13:03:32