【问题标题】:Best practice for consecutive method invocations on the same reference using Dart使用 Dart 对同一引用进行连续方法调用的最佳实践
【发布时间】:2021-05-20 13:45:20
【问题描述】:

当我执行以下操作时,我的 linter 不喜欢它:

final list = []; 

list.add(someItem); 
list.add(anotherItem); 
list.add(thirdItem); 

提示:“在同一个引用上级联连续的方法调用。”

这是首选/更好的做法吗:

final list = []; 

final item1 = someItem;
final item2 = anotherItem; 
final item3 = thirdItem; 

list.addAll([item1, item2, item3]); 

如果是,为什么?

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    lint 建议您使用Cascade operator。此运算符允许您对同一对象进行多个操作。这样您就无需重复调用引用名称(在本例中为 list)。

    这是您的例子,比较两种方式:

      List<int> list= []; 
      list.add(1); 
      list.add(2); 
      list.add(3);
      print (list);
    

    其中,使用级联运算符:

      List<int> list2= [];
      list2..add(1)
           ..add(2)
           ..add(3); // May be done without line breaks, if preferred.
      print(list2);
    

    两个示例都打印相同的输出,这是理想的结果。但第二个感觉更干净,更具可读性。此外,如果您想稍后更改正在使用的对象,则只需在一处进行更改。

    你可以在DartPad上测试它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-26
      • 2018-11-12
      • 2019-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-18
      相关资源
      最近更新 更多