简体   繁体   English

谁能解释一下在 Dart 中使用空短路级联?

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

I'm confused about what the documentation says here:我对文档在这里所说的内容感到困惑:

文档代码截图

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 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`
}

Run on dartPaddartPad上运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是 double 和 Double 在 dart 中是不同的东西,如果是,谁能解释我 - is double and Double are different thing in dart and if it is can anyone explain me 你能解释一下这个 dart json 解析代码吗? - Can you explain this dart json parsing code please? 任何人都可以详细解释这段代码中发生的事情,我被卡住了 - can anyone please explain in details what is happening in this code,i am stuck 谁能解释 function of.map() - Can anyone explain the function of .map() 谁能告诉我如何在Flutter的DropDown Menu中使用本地JSON数据? - Can anyone please tell me how can we use our local JSON data in DropDown Menu in flutter? 任何人都可以在颤振中向我解释这段代码吗? - can anyone explain to me this piece of code in flutter? DART:有人可以向我解释一下这条线吗? - DART: can some explain this line to me? 谁能告诉我如何在没有按钮的情况下使用 function。 Function 应自动触发 - Can Anyone Please Tell me that how to use the function without the button. Function should be triggered automatically 颤动/飞镖:接收器可以是 null - flutter/dart: receiver can be null 这个列表是如何使用地图集成到下拉按钮项目中的?谁能解释一下? - How is this list is integrated in Dropdownbutton items using map?Can anyone explain?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM