错误:
The following NoSuchMethodError was thrown building MyApp(dirty, state: _MyAppState#ad714):
The method 'map' was called on null.
Receiver: null
Tried calling: map<Answer>(Closure: (String) => Answer)
我的代码:
import 'package:flutter/material.dart';
import './qestion.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);
//print('Answer choosen');
}
Widget build(BuildContext context) {
var questions = [
{
'questionText': 'what\'s your favorite color?',
'answers': ['red', 'black', 'brown'],
},
{
'questionText': 'what\s your favorite animal ?',
'answers': ['lion', 'horse'],
},
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('My First Application'),
),
body: Column(
children: [
Question(
questions[_questionIndex]['questionText'],
),
...(questions[_questionIndex]['answer'] as List<String>)
. map((answer) {
return Answer(_answerQuestion, answer);
}).toList()
[],
// RaisedButton(
// child: Text('Answer 2'),
// onPressed: () => {print('it is a =anonymus ans')},
// ),
],
),
),
);
}
}
有问题的部分可能是:
...(questions[_questionIndex]['answer'] as List<String>)
. map((answer) {
return Answer(_answerQuestion, answer);
}).toList()
问题.dart:
import 'package:flutter/material.dart';
class Question extends StatelessWidget {
// const Question({ Key? key }) : super(key: key);
final String questionText;
Question(this.questionText);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(10),
width: double.infinity,
child: Text(
questionText,
style: TextStyle(fontSize: 25),
textAlign: TextAlign.center,
),
);
}
}
答案.dart
import 'package:flutter/material.dart';
class Answer extends StatelessWidget {
//const Answer({ Key? key }) : super(key: key);
final Function selectHandler;
final String answerText;
Answer(this.selectHandler, this.answerText);
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: RaisedButton(
textColor: Colors.black,
color: Colors.cyan,
child: Text(answerText),
onPressed: selectHandler,
));
}
}
如何在 VScode 编辑器中解决此错误?