Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is this operator "?." in Dart?

i work with flutter framework this part of the code use a operation "?." but idont understand

 if (state is WeatherLoaded) {
          final weather = state.weather;
          final themeBloc = BlocProvider.of<ThemeBloc>(context);
          themeBloc.dispatch(WeatherChanged(condition: weather.condition));

          _refreshCompleter?.complete();
          _refreshCompleter = Completer();

all code this link

like image 203
aeon Avatar asked Nov 21 '25 02:11

aeon


1 Answers

The best way to demonstrate this is a simple example.
I have an object SomeObject with one method username.

I have made 2 instances of it:

  • aeonObject which is not null
  • someOtherObject which is null
class SomeObject {
  String username() => "aeon";
}

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

  SomeObject someOtherObject;
  print(someOtherObject.username());
}

If I execute this snippet you'll see the following output.
The program will crash because we tried to execute a method on a null reference.

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()

However if I call the print statement with the ?. aka Conditional member access operator.

print(someOtherObject?.username());

We instead get.

null

like image 104
timr Avatar answered Nov 22 '25 18:11

timr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!