Flutter中使用map函数触发NoSuchMethodError错误求助
问题排查:Flutter中map调用空指针错误
报错信息
Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The method 'map' was called on null. Receiver: null Tried calling: map(Closure: (String) => Answer))
问题代码
import 'package:flutter/material.dart'; import './question.dart'; import 'answer.dart'; void main() { runApp(MyApp()); } class MyApp extends StatefulWidget { @override State<StatefulWidget> createState() { return MyAppState(); } } class MyAppState extends State<MyApp> { var questionIndex = 0; void answerquestion() { setState(() { if (questionIndex < 1) { questionIndex = questionIndex + 1; } }); print("answer question!"); } @override Widget build(BuildContext context) { var questions = [ { "questionText": "where are you from?", "answers": ["berlin ", "london", "DC", "new york"] }, { "questionText": "what is your favourite color?", "answers": [" purple", "red", "yellow ", "blue"] } ]; return MaterialApp( home: Scaffold( appBar: AppBar( title: Text("jini question"), ), body: Column(children: [ Question( questions[questionIndex]["questionText"], ), ...(questions[questionIndex]["answer"] as List<String>).map((answer) { return Answer(answerquestion, answer); }).toList() ]), ), ); } }
解决方法
核心错误:键名拼写错误
你在获取答案列表时使用了键名"answer",但定义的questions数组里,存储答案的键是"answers"(复数形式)。这导致questions[questionIndex]["answer"]返回null,调用map方法时触发空指针异常。
修正代码:将questions[questionIndex]["answer"]改为questions[questionIndex]["answers"]。可选:添加空安全兜底
为了避免后续类似的null问题,可以增加空检查,确保即使键不存在也不会崩溃:...((questions[questionIndex]["answers"] as List<String>?) ?? []).map((answer) { return Answer(answerquestion, answer); }).toList()
内容的提问来源于stack exchange,提问作者base leader
相关产品推荐
相关产品推荐

