a shot of dev knowledge

RELATED TAGS

What is Dart cascade notation?

svg viewer

The cascade notation (. .) in Dart allows you to make a sequence of operations on the same object (including function calls and field access). This notation helps keep Dart code compact and removes the need to create temporary variables to store data.

Code

In the example below, we have created an Example class with two methods:

  • bSetter
  • printValues

In line 24-27, we are using dart cascade notation for operations on Example class object eg1.

import 'dart:convert';

//An Example class with member attributes and methods
class Example{
  var a;
  var b;
  void bSetter(b)
  {
    this.b = b;
  }
  void printValues(){
    print(this.a);
    print(this.b);
  }
}

void main() {
    //Instantiating two Example objects
    Example eg1 = new Example();
    Example eg2 = new Example();

    //Using the .. operator for operations on Example object
    print("Example 1 results:");
    eg1
    ..a = 88
    ..bSetter(53)
    ..printValues();

    //The same operations as above but without the .. operator
    print("Example 2 results:");
    eg2.a = 88;
    eg2.bSetter(53);
    eg2.printValues();
}

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring