Flutter报错NoSuchMethodError:map方法被调用在null对象上求助
问题解决方案
核心错误原因
你遇到的NoSuchMethodError是因为键名不匹配:
- 定义
questions数组时,每个对象的答案字段是'answer'(单数) - 但代码中调用时写成了
questions[_questionIndex]['answers'](复数,多了个s),导致获取到null,调用map方法时触发错误。
额外需要修复的边界问题
当用户多次点击答案后,_questionIndex会持续递增,最终超过questions数组的长度,触发数组越界错误。需要添加判断逻辑避免这种情况。
修改后的完整代码
import 'package:flutter/material.dart'; import './question.dart'; import 'answer.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { var _questionIndex = 0; void _answerQuestion() { setState(() { // 限制索引不超过问题列表长度 if (_questionIndex < questions.length - 1) { _questionIndex++; } }); print(_questionIndex); } // 把questions移到build外,避免每次build都重新创建 final List<Map<String, Object>> questions = [ { 'questionText': 'What\'s your favorite color?', 'answer': ['Black', 'White', 'Red', 'Green', 'Yellow'], }, { 'questionText': 'What\'s your favorite animal?', 'answer': ['Rabbit', 'Snake', 'Monkey', 'Lion', 'Dog'], }, { 'questionText': 'Who\'s your favorite instructor?', 'answer': ['Max', 'Joel', 'Emma', 'Moses', 'Jones'], }, ]; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: const Text('My App'), ), body: _questionIndex < questions.length ? Column( children: [ Question(questions[_questionIndex]['questionText'] as String), // 修正键名为'answer' ...(questions[_questionIndex]['answer'] as List<String>) .map((answer) { return Answer(_answerQuestion, answer); }).toList(), ], ) : // 所有问题回答完毕后显示的页面 const Center( child: Text('You\'ve answered all questions!'), ), ), ); } }
其他优化点
- 将
questions变量移到build方法外部,避免每次组件重建时重复创建列表,提升性能。 - 添加
const关键字优化无状态组件(如AppBar的Text)。
内容的提问来源于stack exchange,提问作者CyberEmperor
相关产品推荐
相关产品推荐

