flutter - Dart 中的这个运算符 "?."是什么?

标签 flutter dart operators

我使用 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
  • someOtherObjectnull
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/

相关文章:

flutter - 如何在行中放置容器

dart - Flutter:Facebook 和 Google 身份验证

firebase - Flutter:方法[]在null上被调用

php - "Operator"优先级?为什么 new Object()->method() 在 PHP 中会出现语法错误?

android - 我希望我的 flutter 应用程序在 android 设备启动后自动启动

flutter - 如何在 flutter slider 小部件上隐藏拇指?

dart - 如何在 flutter 中使用 Google API?

flutter - 退出后如何回到应用程序的起点?

flutter - 可以用吗??在这种情况下是运营商?

c++ - 创建用户数据库错误 "no match for ' operator= =' in....."--C++