I'm new to flutter , or programming to be clear . I was following a course , doing the same as the Instructor , the app worked for him , but when i try to run it ,this error shows up .
// @dart=2.9
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import './question.dart';
import './answer.dart';
class Quiz extends StatelessWidget {
final List<Map<String, Object>> questions;
final int questionIndex;
final Function answerQuestion;
Quiz(
{@required this.questions,
@required this.answerQuestion,
@required this.questionIndex});
@override
Widget build(BuildContext context) {
return ListView(
children: [
Question(
questions[questionIndex]['questionText'],
),
...(questions[questionIndex]['answers'] as List<Map<String, Object>>)
.map((answer) {
return Answer(() => answerQuestion(answer['score']), answer['text']);
}).toList()
],
);
}
}
This means that your map has a null value somewhere. Change your code to this:
Answer(() => answerQuestion(answer['score']??"NA"), answer['text']??"NA");
The problem is propably that the person from the course uses an older version of Flutter which doesn't use null safety . So to solve this you need to migrate your code to null safety. For more information on how and when to use null safety you can refer to this great video from Robert Brunehage . The Fixes you need to do on your code are the following:
1. change @required
to required
2. add a question Mark to variables that don't have a value,
Bad example:
int questionIndex;
This will lead to a null error because name
doesnt have a value (means it is null)
Correct example
int? questionIndex;
This variable is now null safe which prevents it from ending up with an error.
3. after you've now made your variables without a default value null safe you have to add !
at some places (your IDE should show you where to add it normally)
Wrong code:
questions[questionIndex]['questionText'],
Correct code
questions[questionIndex!]['questionText'],
If you don't want to use Null safety (not recommended!)
you can give your Widget a default Text in case your variable has no value (is null)
Question(questions[questionIndex]['questionText']?? "default value",),
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.