i'm new to programming and was following an older course that has no null-safety . i tried to solve the problem by insertin a default value , but that just made all the texts on the buttons have the word "default value" on them .
// @dart=2.9
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.red.shade400,
textColor: Colors.white,
child: Text(answerText?? 'default value'),
onPressed: selectHandler,
));
}
}
EDIT :
the Answer class gets called here :
// @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']?? "default value",
),
...(questions[questionIndex]['answers'] as List<Map<String, Object>>)
.map((answer) {
return Answer(() => answerQuestion(answer['score']), answer['text']);
}).toList()
],
);
}
}
Solution 1: ImPiNoron
In null-safety dart, a String
will never be null so you can't use ??
after a string. However, you can define answerText
as a String?
which will make it a nullable string. For more details, you can check this website.
The above explanation can make the program run but setting default values everywhere is not a good coding style. It will cause a lot of troubles when you or your team is trying to debug your code. in A better practice would be setting default values when initiating the object:
class Answer extends StatelessWidget {
final void Function()? selectHandler;
final String answerText;
Answer(void Function()? selectHandler, String? answerText)
: selectHandler = selectHandler,
answerText = answerText ?? 'default value';
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
child: RaisedButton(
color: Colors.red.shade400,
textColor: Colors.white,
child: Text(answerText),
onPressed: selectHandler,
));
}
}