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

Flutter 1.71.1报错:‘Null’不是‘List<String>’子类型的类型转换问题

解决Flutter中“type 'Null' is not a subtype of type 'List' in type cast”错误

问题根源

你的代码存在两个核心问题:

  1. 键名拼写错误:定义questions数组时,每个map的答案键是'answer',但调用时写成了'answers'(多了一个s),导致取值为null,强制转换为List<String>时触发类型错误。
  2. 未处理索引越界:当点击次数过多,_questionIndex超过questions数组长度时,questions[_questionIndex]会返回null,后续类型转换同样会报错。

修复步骤

  1. 修正键名:将代码中questions[_questionIndex]['answers']改为questions[_questionIndex]['answer']。
  2. 添加空值与越界判断:在取值前先检查索引是否有效,同时用??提供默认空列表,避免强制转换null。

修正后的完整代码

import 'package:flutter/material.dart';

import './question.dart';
import './answer.dart';

void main() => runApp(const MyApp());

class MyApp extends StatefulWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var _questionIndex = 0;

  void _answerQuestion() {
    setState(() {
      // 限制索引不超过问题数量-1,避免越界
      if (_questionIndex < questions.length - 1) {
        _questionIndex += 1;
      } else {
        // 可选:重置索引回到第一个问题
        _questionIndex = 0;
      }
    });
    print(_questionIndex);
  }

  // 将questions提取到build外,避免每次build都重新创建
  final List<Map<String, Object>> questions = [
    {
      'questionText': 'Who created Flutter?',
      'answer': ['Google', 'Yahoo', 'Amtrak', 'Disney'],
    },
    {
      'questionText': 'What is your favorite class',
      'answer': ['Java', 'Mobile App', 'Dart', 'DevOps'],
    },
    {
      'questionText': 'What is your favorite Flutter feature',
      'answer': ['Class', 'Functions', 'Dart', 'Widgets'],
    },
  ];

  @override
  Widget build(BuildContext context) {
    // 先获取当前问题,处理索引越界情况
    final currentQuestion = _questionIndex < questions.length 
        ? questions[_questionIndex] 
        : {'questionText': 'No more questions', 'answer': []};

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Flutter Quiz'),
        ),
        body: Column(
          children: [
            Question(currentQuestion['questionText'] as String),
            // 使用??提供默认空列表,避免null强制转换
            ...((currentQuestion['answer'] as List<String>?) ?? []).map((answer) {
              return Answer(_answerQuestion, answer);
            }).toList()
          ],
        ),
      ),
    );
  }
}

额外优化建议

  • 将questions数组移到build方法外,避免每次组件重建都重新创建列表,提升性能。
  • 添加索引重置逻辑,当所有问题答完后回到第一个问题,提升用户体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 10:55:15