'Can anyone please explain the use of null-shorting cascade in Dart?

I'm confused about what the documentation says here:

documentation code screenshot

Solution 1:[1]

Example class

class Foo {
  String? text;
  List<String> classes = [];

  String toString() {
    return "text $text classLength ${classes.length}";

querySelector can return null instead of Foo

Foo? querySelector({required bool retunNull}) {
  return retunNull ? null : Foo();
void main(List<String> args) {
  /// `querySelector` can return  null Foo
  Foo? foo = querySelector(retunNull: true);

  // foo can be null, that's we cant directly use `text`
  // if we use `!`, it means we are sure that `foo` is not null.
  // but we cant be sure because `querySelector` can return null,
  // therefore we use `?` means, if left side is null simply retun exit from this expression
  foo?.text = "Confirm";

  //same here,

  /// now our `foo` object will contain `text=Confirm` and a class `c1`
  ///* only if `foo` isnot null
  print(foo);// print null

  /// Now the short version
  /// we use `..` to perform multiple operation on single line
  /// while the `querySelector` can retun null
  ///  we need to use `?..` means exit the expression if `querySelector` retun null.
  Foo? foo1 = querySelector(retunNull: true)
    ?..text = "Confirm1"

  print(foo1);// print null

  Foo? foo2 = querySelector(retunNull: false)
    ?..text = "Confirm2"

  print(foo2);// print `text Confirm2 classLength 1`

Run on dartPad


This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yeasin Sheikh