Dart Operators : Cascade Notation

Dart Operators : Cascade Notation

Cascade notation allows you to perform multiple operations on a single object without the need for the methods to return this.

Here's a simple example to illustrate how cascade notation works:

dartCopy codeclass ShoppingCart {
  List<String> items = [];

  void addItem(String item) {
    items.add(item);
  }

  void removeItem(String item) {
    items.remove(item);
  }

  void displayItems() {
    print('Items in the shopping cart:');
    for (var item in items) {
      print('- $item');
    }
  }
}

void main() {
  var cart = ShoppingCart();

  // Without cascade notation
  cart.addItem('Apple');
  cart.addItem('Banana');
  cart.displayItems();

  // With cascade notation
  cart
    ..addItem('Orange')
    ..addItem('Grapes')
    ..removeItem('Banana')
    ..displayItems();
}

The use of cascade notation (..) allows us to call multiple methods on the same object (cart) without repeating the object name for each method call. This makes the code more concise and readable.