DEV Community

kalokli8
kalokli8

Posted on

Dart cascade notation (..) and usage in list

A bit introduction: according to dart.dev:

Cascades (.., ?..) allow you to make a sequence of operations on the same object. In addition to accessing instance members, you can also call instance methods on that same object. This often saves you the step of creating a temporary variable and allows you to write more fluid code.

var paint = Paint()
  ..color = Colors.black
  ..strokeCap = StrokeCap.round
  ..strokeWidth = 5.0;
Enter fullscreen mode Exit fullscreen mode

The constructor, Paint(), returns a Paint object. The code that follows the cascade notation operates on this object, ignoring any values that might be returned.

The previous example is equivalent to this code:

var paint = Paint();
paint.color = Colors.black;
paint.strokeCap = StrokeCap.round;
paint.strokeWidth = 5.0;
Enter fullscreen mode Exit fullscreen mode

You can also not assign the value and just run some functions.
Let's play around and see these examples:

class Cat {
  String sound() => 'hi';
  String sound2() => 'hi2';
}

void main() {
  // Create a Cat instance
  final cat = Cat();

  print(cat.sound()); // 'hi'
  print(cat..sound()..sound2()); // Instance of 'Cat'


  print([]..add(1)); // [1]

  print([].add(1));
  // Error: This expression has type 'void' and can't be used.
  // You can't print void value.

  [].add(1); 
  // The array is [1].The add method returns 
  // void and the value is not assigned to any variable.



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

  // It is equivalent:
  List<int> num2 = [1]..add(2)..add(3);
  print(num2);
  // [1,2,3]

}
Enter fullscreen mode Exit fullscreen mode

Finally, I find this link useful when encounter errors of
'Cannot add to an unmodifiable list' or 'The default value of an optional parameter must be constant':

https://stackoverflow.com/questions/66550202/how-to-add-to-an-existing-list-got-unsupported-operation-cannot-add-to-an-unm

Basically it means the 'const' keyword makes the list unmodifiable. You can use spread operator(...) or List.from() to make a new array to solve this problem.

chat.messages = [...chat.messages, message];
chat.messages = List.from(chat.messages)..add(message);

Top comments (0)