Flutter运行报错NoSuchMethodError:null对象调用iterator/map方法
解决Flutter运行时NoSuchMethodError错误
错误原因
- 键名拼写错误:数据集合中存储答案的键是
'answer',但代码里误写为'answerkey',导致获取到null,调用.map()方法时触发NoSuchMethodError(null没有iterator属性)。 - 索引越界风险:点击答案后
_questionIndex持续累加,当超过question数组长度时,question[_questionIndex]会返回null,同样会引发类似错误。
修复方案
1. 修正键名拼写
打开main.dart,找到map方法调用的行,将'answerkey'改为'answer':
...(question[_questionIndex]['answer'] as List<String>) .map((answer) { return Answer(_answerQuestion, answer); }).toList()
2. 限制索引范围,避免越界
首先把question数组从build方法内移到类成员位置(避免每次build重新创建),然后修改_answerQuestion方法,限制索引最大值:
class _MyAppState extends State<MyApp> { var _questionIndex = 0; // 将question改为类成员变量 final List<Map<String, dynamic>> question = [ { 'questionKey': 'who is your friend?', 'answer': ['Jermmy', 'hanna', 'steve', 'lee yu'] }, { 'questionKey': 'where are you from ', 'answer': ['berlin', 'newyork', 'paris'] }, { 'questionKey': 'what is your job', 'answer': ['teacher', 'doctor', 'driver'] } ]; void _answerQuestion() { setState(() { // 索引不超过数组最后一位 if (_questionIndex < question.length - 1) { _questionIndex += 1; } // 可选:如果需要循环展示题目,取消下面注释 // else { // _questionIndex = 0; // } }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("AppBar"), ), body: Column( children: [ Question(question[_questionIndex]['questionKey']), ...(question[_questionIndex]['answer'] as List<String>) .map((answer) { return Answer(_answerQuestion, answer); }).toList() ], ), ), ); } }
3. 可选:增强代码健壮性(添加空值判断)
为避免意外null引发错误,可以在获取数据时添加空值兜底:
body: Column( children: [ Question(question[_questionIndex]['questionKey'] ?? '暂无题目'), ...((question[_questionIndex]['answer'] as List<String>?) ?? []).map((answer) { return Answer(_answerQuestion, answer); }).toList() ], ),
内容的提问来源于stack exchange,提问作者Miles
相关产品推荐
相关产品推荐

