James
James

Reputation: 671

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

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

final list = []; 

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

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

Is it preferred / better practice to do:

final list = []; 

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

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

If so, why?

Upvotes: 3

Views: 3239

Answers (1)

Naslausky
Naslausky

Reputation: 3768

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.

Upvotes: 4

Related Questions