Flutter 1.71.1报错:‘Null’不是‘List<String>’子类型的类型转换问题
解决Flutter中“type 'Null' is not a subtype of type 'List' in type cast”错误
问题根源
你的代码存在两个核心问题:
- 键名拼写错误:定义
questions数组时,每个map的答案键是'answer',但调用时写成了'answers'(多了一个s),导致取值为null,强制转换为List<String>时触发类型错误。 - 未处理索引越界:当点击次数过多,
_questionIndex超过questions数组长度时,questions[_questionIndex]会返回null,后续类型转换同样会报错。
修复步骤
- 修正键名:将代码中
questions[_questionIndex]['answers']改为questions[_questionIndex]['answer']。 - 添加空值与越界判断:在取值前先检查索引是否有效,同时用
??提供默认空列表,避免强制转换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
相关产品推荐
相关产品推荐

