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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 11:10:24