Three new language features just landed in the latest dev channel build of the
Dart! Collectively known as
null-aware operators, these new features will help you reduce the code required to work with potentially null objects.
I'm excited for these new abilities, because typing less is always a good thing. Read on to learn more, and be sure to try these new features on
Dart Pad.
??
Use ?? when you want to evaluate and return an expression IFF another expression resolves to null.
exp ?? otherExp
is similar to
((x) => x == null ? otherExp : x)(exp)
??=
Use ??= when you want to assign a value to an object IFF that object is null. Otherwise, return the object.
obj ??= value
is similar to
((x) => x == null ? obj = value : x)(obj)
?.
Use ?. when you want to call a method/getter on an object IFF that object is
not null (otherwise, return null).
obj?.method()
is similar to
((x) => x == null ? null : x.method())(obj)
You can chain ?. calls, for example:
…