簡體   English   中英

誰能解釋一下在 Dart 中使用空短路級聯?

[英]Can anyone please explain the use of null-shorting cascade in Dart?

我對文檔在這里所說的內容感到困惑:

文檔代碼截圖

示例類

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

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

querySelector可以返回 null 而不是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`
}

dartPad上運行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM