[英]A non-null String must be provided to a Text widget . error shows but null-safety doesn't make it for the code
i'm new to programming and was following an older course that has no null-safety .我是编程新手,正在学习没有 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 :在这里调用 Answer 类:
// @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()
],
);
}
}
In null-safety dart, a String
will never be null so you can't use ??
在空安全飞镖中, String
永远不会为空,因此您不能使用??
after a string.在一个字符串之后。 However, you can define answerText
as a String?
但是,您可以将answerText
定义为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,
));
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.