DEV Community


Posted on

Dart cascade notation (..) and usage in list

A bit introduction: according to

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 =
  ..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 =;
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]

  // Error: This expression has type 'void' and can't be used.
  // You can't print void value.

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

  List<int> num = [1];
  // [1,2,3]

  // It is equivalent:
  List<int> num2 = [1]..add(2)..add(3);
  // [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':

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 = [, message];
chat.messages = List.from(chat.messages)..add(message);

Top comments (0)