这个运算符“?”是什么?在飞镖?
What is this operator "?." in 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();
全部代码thislink
检查此 link:Language tour
?.
Conditional member access
Like ., but the leftmost operand can be null; example: foo?.bar
selects property bar from expression foo unless foo is null (in which
case the value of foo?.bar is null)
证明这一点的最好方法是一个简单的例子。
我有一个对象 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()
但是,如果我用 ?.
又名 Conditional member access operator
.
调用 print
语句
print(someOtherObject?.username());
我们反而得到了。
null
我使用 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();
全部代码thislink
检查此 link:Language tour
?.
Conditional member access
Like ., but the leftmost operand can be null; example: foo?.bar selects property bar from expression foo unless foo is null (in which case the value of foo?.bar is null)
证明这一点的最好方法是一个简单的例子。
我有一个对象 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()
但是,如果我用 ?.
又名 Conditional member access operator
.
print
语句
print(someOtherObject?.username());
我们反而得到了。
null