Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

flutter

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?

like image 436
James Avatar asked Nov 27 '25 07:11

James


1 Answers

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.

like image 74
Naslausky Avatar answered Nov 29 '25 12:11

Naslausky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!