[英]Flutter conditional rendering with null-safety
如果过期不是 null,我想呈现文本小部件。 所以我检查了 null
但是得到了错误
class TileButton extends StatelessWidget {
final DateTime? expires;
const TileButton({
Key? key,
this.expires,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Row(
children: [
Text(
'Hello Flutter',
),
if (expires != null)
Text(
expires.day.toString(),
),
],
);
}
}
感谢社区的人。 他显示我应该看的地方
因此,此检查不适用于 class 字段
分析仪无法 model 整个应用程序的流程,因此无法预测全局变量或 class 字段的值。
对于非局部变量,编译器无法轻易做出保证。 非局部变量隐含地提供 getter 函数,这些函数可以被派生的 class 覆盖,并且可以从一次访问返回不同的值到下一次访问。
另请查看此帖子评论中的链接以获取更多信息
所以。 如果我想使用 null 检查而不使用! 我应该创建本地 var final _expires = expires; 并使用 _expires 进行检查
class TileButton extends StatelessWidget {
final DateTime? expires;
const TileButton({
Key? key,
this.expires,
}) : super(key: key);
@override
Widget build(BuildContext context) {
final _expires = expires;
return Row(
children: [
Text(
'Hello Flutter',
),
if (_expires != null)
Text(
_expires.day.toString(),
),
],
);
}
}
您正在使用 Flutter 并启用了空值安全。 (如果这个概念对您来说是新概念,请在 Flutter 中阅读Null 安全性。)
该错误似乎是在抱怨在表达式expires.day.toString()
中,术语expires
可以是 null,这在 null 安全中是不允许的。 您知道expires
不是 null,因此您可以断言以防止错误使用!
如expires..day.toString()
。
注意,在简单的 Dart 代码中,编译器检测到非空的测试,并且不报告错误,例如:
DateTime? test;
print('${test.day}');
if (test != null) {
print('${test.day}');
}
var list = [
test.day,
if (test != null) test.day,
];
这里第一个和第三个打印语句有错误,第二个和第四个没有。 我不知道为什么这不会进入 Text 小部件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.