What does ?. do in Dart?

1,593

Solution 1

It's a null safe operator.

Use ?. when you want to call a method/getter on an object IF that object is not null (otherwise, return null).

_drawerKey.currentState?.open();

Call open() only if it's not null.

More info: https://medium.com/@thinkdigitalsoftware/null-aware-operators-in-dart-53ffb8ae80bb

Solution 2

To guard access to a property or method of an object that might be null, put a question mark (?) before the dot (.):

myObject?.anyProperty

The preceding code is equivalent to the following:

(myObject != null) ? myObject.anyProperty: null

You can chain multiple uses of ?. together in a single expression:

myObject?.anyProperty?.anyMethod()

The preceding code returns null (and never calls anyMethod()) if either myObject or myObject.anyProperty is null.

For more, read offcial docs,

Share:
1,593
Landon
Author by

Landon

Updated on December 16, 2022

Comments

  • Landon
    Landon over 1 year

    What does "?." syntax do in Dart language? I have here an example from Flutter's scaffold.dart code:

    _drawerKey.currentState?.open();