gpt4 book ai didi

flutter - 空检查不会在Dart中引起类型提升

转载 作者:行者123 更新时间:2023-12-03 13:28:35 24 4
gpt4 key购买 nike

我正在升级基于Flutter框架的个人软件包。我在Flutter Text小部件源代码中注意到here,存在一个空检查:

if (textSpan != null) {
properties.add(textSpan!.toDiagnosticsNode(name: 'textSpan', style: DiagnosticsTreeStyle.transition));
}
但是, textSpan!仍在使用 !运算符。无需将 textSpan提升为非可空类型,而不必使用 !运算符吗?但是,尝试删除该运算符将产生以下错误:
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.

这是一个独立的示例:
class MyClass {
String? _myString;

String get myString {
if (_myString == null) {
return '';
}

return _myString; // <-- error here
}
}
我收到一个编译时错误:

Error: A value of type 'String?' can't be returned from function 'myString' because it has a return type of 'String'.


或者,如果我尝试获取 _mySting.length,则会出现以下错误:

The property 'length' can't be unconditionally accessed because the receiver can be 'null'.


我以为执行空检查将把 _myString提升为非空类型。为什么不呢?
My question已在GitHub上解决,因此我在下面发布了答案。

最佳答案

Dart 工程师Erik Ernst says on GitHub:

Type promotion is only applicable to local variables. ... Promotion of an instance variable is not sound, because it could be overridden by a getter that runs a computation and returns a different object each time it is invoked. Cf. dart-lang/language#1188 for discussions about a mechanism which is similar to type promotion but based on dynamic checks, with some links to related discussions.


因此,本地类型推广工作:
  String myMethod(String? myString) {
if (myString == null) {
return '';
}

return myString;
}
但是实例变量不会升级。为此,您需要使用 !运算符手动告诉Dart您确保实例变量在这种情况下不为null:
class MyClass {
String? _myString;

String myMethod() {
if (_myString == null) {
return '';
}

return _myString!;
}
}

关于flutter - 空检查不会在Dart中引起类型提升,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65035574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com