[英]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.