Search code examples
flutterdartoperatorsdart-null-safety

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

  • Example class

    class Foo {
      String? text;
      List<String> classes = [];
    
      @override
      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,
      foo?.classes.add("cls");
    
      /// 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"
        ..classes.add("cls1");
    
      print(foo1);// print null
    
      Foo? foo2 = querySelector(retunNull: false)
        ?..text = "Confirm2"
        ..classes.add("cls2");
    
      print(foo2);// print `text Confirm2 classLength 1`
    }
    

    Run on dartPad