Flutter / Dart / NoSuchMethodError

问题描述 投票:0回答:1

我两个小时都无法解决该错误。也许你们之一可以帮助我。您可以在下面找到照片。

调试控制台还告诉我:

[ The following NoSuchMethodError was thrown building MyApp (dirty, state: _MyAppState#c7f7e):
I/flutter (17681): The method 'map' was called on null.
I/flutter (17681): Receiver: null
I/flutter (17681): Tried calling: map<Answer>(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(() {
      _questionIndex = _questionIndex + 1;
    });
    print(_questionIndex);
  }

  @override
  Widget build(BuildContext context) {
    const questions = const [
      {
        'questionText': 'What\'s your favorite color?',
        'answer': ['Black', 'Yellow', 'white', 'green'],
      },
      {
        'questionText': 'What\'s your favorite animal?',
        'answer': ['Lion', 'Rabbit', 'Snake', 'Elephant'],
      },
      {
        'questionText': 'What\'s your favorite instructor?',
        'answer': ['Flo', 'Viona', 'Flint', 'Flo'],
      },
    ];

    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('My First App!'),
        ),
        body: Column(
          children: [
            Question(
              questions[_questionIndex]['questionText'],
            ),
            ...(questions[_questionIndex]['answers'] as List<String>)
                .map((answer) {
              return Answer(_answerQuestion, answer);
            }).toList()
          ],
        ),
      ),
    );
  }
}

import 'package:flutter/material.dart';

//import './main.dart';

class Question extends StatelessWidget {
  final String questionText;

  Question(this.questionText);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.all(10),
      child: Text(
        questionText,
        style: TextStyle(fontSize: 28),
        textAlign: TextAlign.center,
      ),
    );
  }
}

import 'package:flutter/material.dart';

class Answer extends StatelessWidget {
  final Function selectHandler;
  final String answerText;

  Answer(this.selectHandler, this.answerText);

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      child: RaisedButton(
        color: Colors.blue,
        textColor: Colors.white,
        child: Text(answerText),
        onPressed: selectHandler,
      ),
    );
  }
}

That shows me the app

flutter dart error-handling
1个回答
0
投票

您的地图中没有名为answers的键。相反,它称为answer。因此,questions[_questionIndex]['answers']将返回null,因为[]Map运算符记录为:

返回给定键的值;如果键不在映射中,则返回null。

https://api.dart.dev/stable/2.8.3/dart-core/Map/operator_get.html

© www.soinside.com 2019 - 2024. All rights reserved.