Question mark before dot in Dart

2020-03-31 07:08发布

问题:

What's the meaning of the question mark in this piece of code? And when am I supposed to use it? My code functions the same way with or without the question mark.

void dispose(){
  bloc?.dispose();
  super.dispose();
}

回答1:

The question mark is one of the null-aware operators in Dart. In this example it says: call the dispose() method only if bloc is not null. Without the question mark, if bloc was null when it tried to call dispose() a NoSuchMethodError would be thrown.

There is a useful section on the Dart site about null-aware operators:

https://dart.dev/codelabs/dart-cheatsheet



标签: syntax dart bloc