How to use double dot operator- Cascade operator in Dart| Flutter

cascade operator is used to call sequence of methods on the objects using .. double dot operator.

For example, you have a list object and want to call the same add method for multiple values.

You will call as below

List list = [];

The object name list is repeatedly called to do the same operation. You can also do multiple operations on the same object. Cascade operator (..) is introduced to avoid the repeated current object instance name.

Dart Cascade operator

The Cascade operator is also called the double dot operator.

It is used to chain operations piped using double dot by ignoring return values.



instance..method1 returns this object.

The same can be rewritten using

main() {
  List list = [];

It is helpful for developers to build objects faster with few lines of code.

Null Shorting Cascade notation for null safety in dart

Sometimes, the Object that you call the double dot operator might be null, In that case, a null shorting cascade(? ..) is being used.

var employee = Employee();
employee.id = 1;
employee.name ="John";
employee.salary = 5000;

The above code was replaced with a cascade operation

var employee = Employee()
..id = 1;
..name ="John";
..salary = 5000;

Next, add the null shorting operator(?) for the first cascade operation for null safety

var employee = Employee()
?..id = 1;
..name ="John";
..salary = 5000;

which is equal to

var employee = Employee();
employee?.id = 1;
employee?.name ="John";
employee?.salary = 5000;
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
You'll get a notification every time a post gets published here.

Related posts

Dart| Flutter How to: Read pubspec.yaml attributes (version) with examples

How to Create and build a Singleton Class Dart or Flutter example| Dart By Example

What is the difference between var and dynamic and final in dart?| Flutter By Example

How to: Check if Phone number is valid or not in Dart| Flutter By Example

Dart| Flutter How to read an image from a disk and resize a file

Dart/Flutter: How to write setter and getter fields or members variables in a class with Example

Dart| Flutter How to get extension name and MIME type of a file with example