我正在升级一个基于 Flutter 框架的个人包。我在 Flutter Text 小部件源代码中注意到这里有一个空检查:
if (textSpan != null) {
properties.add(textSpan!.toDiagnosticsNode(name: 'textSpan', style: DiagnosticsTreeStyle.transition));
}
Run Code Online (Sandbox Code Playgroud)
但是,textSpan!仍然使用!运算符。不textSpan应该在不必使用!运算符的情况下提升为不可为空的类型吗?但是,尝试删除运算符会出现以下错误:
Run Code Online (Sandbox Code Playgroud)An expression whose value can be 'null' must be null-checked before it can be dereferenced. Try checking that the value isn't 'null' before dereferencing it.
这是一个独立的示例:
An expression whose value can be 'null' must be null-checked before it can be dereferenced.
Try checking that the value isn't 'null' before dereferencing it.
Run Code Online (Sandbox Code Playgroud)
我收到一个编译时错误:
错误:“字符串?”类型的值 …
如果过期不为空,我想渲染文本小部件。所以我检查了 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(),
),
],
);
}
}
Run Code Online (Sandbox Code Playgroud)