Cascade operator in flutter

Cascade operator in flutter

learn how to use the cascade operator for more productivity

Table of contents

No heading

No headings in the article.

The .. operator in Dart is called the cascade operator. It is used to chain together multiple methods calls on the same object. For example, the following code:

class Person {
  String? name;
  int? age;

  Person({this.name, this.age});

  void setName(String newName) {
    name = newName;
  }

  void setAge(int newAge) {
    age = newAge;
  }
}
void main() {
 Person person = Person();//create a Person object
 person.setName('john');//set name to john
 person.setAge(20);//set age to 20
}

The code above is a class Person that has 2 methods setName and setAge, we created a Person object and used the class method on it.

But we can do better by using a cascade operator instead therefore the code below achieves the same thing.

void main() {
 Person person = Person()..setName('john')..person.setAge(20);
//name and age are set to john and 20 respectfully
}

Let us look at another example

var list = [1, 3, 2];
list.add(4);//adds 4 to the list
list.sort();//sorts the list

Can be rewritten as

var list = [1, 3, 2];
list..add(4)..sort();//4 is added and then the list sorted

Cascade operators could make your code look nicer and more compact and this is something you should certainly include in your next project when calling different functions on the same object.

See you in my next article.