Best practice for consecutive method invocations on the same reference using Dart

Total
1
Shares

My linter doesn’t like it when I do something like:

_x000D_

_x000D_

final list = []; 

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

_x000D_

_x000D_

_x000D_

hint: "Cascade consecutive method invocations on the same reference."

Is it preferred / better practice to do:

_x000D_

_x000D_

final list = []; 

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

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

_x000D_

_x000D_

_x000D_

If so, why?


Solution

The lint is suggesting you to use the Cascade operator. This operator allows you to make multiple operations on the same object. This way you won’t need to repeat the call to the reference name (in this case, list).

Here is an example in your case, comparing both ways:

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

Where, using the cascade operator:

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

Both examples prints the same output, which is the desirable result. But the second one feels cleaner and more readable. Also, if you want to later change which object is being used, you have to change it in only one place.

You can test it on DartPad.

Leave a Reply

Your email address will not be published. Required fields are marked *