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

How to iterate loop Enum in Dart | Get Enum with index in Flutter By Example

Dart Enum comparison operator| Enum compareByIndex example| Flutter By Example

Dart tutorial examples/ Flutter By Examples

How to add Methods or Values to Enums in Dart | Flutter By Example

How to convert Double to Integer or Integer to double in Dart| Flutter By Example

How to: Enum to String in Dart | Print Enum name as String in Flutter By Example

Dart| Flutter How to get File name and extension with example