这个运算符“?”是什么?在飞镖?

aeo*_*eon 3 operators dart 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();
Run Code Online (Sandbox Code Playgroud)

所有代码链接

tim*_*tim 5

证明这一点的最好方法是一个简单的例子。
我有一个SomeObject具有一种方法的对象username

我做了两个实例:

  • aeonObject 这不是 null
  • someOtherObject 这是 null
class SomeObject {
  String username() => "aeon";
}

void main() {
  final aeonObject = SomeObject();
  print(aeonObject.username());

  SomeObject someOtherObject;
  print(someOtherObject.username());
}
Run Code Online (Sandbox Code Playgroud)

如果我执行此代码段,您将看到以下输出。
程序会崩溃,因为我们试图在null引用上执行一个方法。

dart lib/main.dart lib/main.dart:警告:将此解释为包 URI,'package:sample/main.dart'。

永世

未处理的异常:NoSuchMethodError:在 null 上调用了方法“用户名”。

接收者:空尝试调用:用户名()

但是,如果我print?.aka调用该语句Conditional member access operator

print(someOtherObject?.username());
Run Code Online (Sandbox Code Playgroud)

我们反而得到。

空值