我使用 flutter 框架 这部分代码使用了一个操作“?”。但我不明白
if (state is WeatherLoaded) {
final weather = state.weather;
final themeBloc = BlocProvider.of<ThemeBloc>(context);
themeBloc.dispatch(WeatherChanged(condition: weather.condition));
_refreshCompleter?.complete();
_refreshCompleter = Completer();
所有代码 this链接
最佳答案
证明这一点的最好方法是一个简单的例子。
我有一个对象 SomeObject
和一个方法 username
。
我已经制作了 2 个实例:
aeonObject
不是null
someOtherObject
为null
class SomeObject {
String username() => "aeon";
}
void main() {
final aeonObject = SomeObject();
print(aeonObject.username());
SomeObject someOtherObject;
print(someOtherObject.username());
}
如果我执行此代码段,您将看到以下输出。
程序将崩溃,因为我们试图在 null
引用上执行方法。
dart lib/main.dart lib/main.dart: Warning: Interpreting this as package URI, 'package:sample/main.dart'.
aeon
Unhandled exception: NoSuchMethodError: The method 'username' was called on null.
Receiver: null Tried calling: username()
但是,如果我使用 ?.
调用 print
语句,又名 条件成员访问运算符
。
print(someOtherObject?.username());
我们反而得到了。
null
关于flutter - Dart 中的这个运算符 "?."是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58362873/