{

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


Dart and Flutter cascade operator example

cascade operator is used to call a 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 = [];
list.add(1);
list.add(2);
list.add(3);
list.add(4);

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 a double dot by ignoring return values.

Syntax.

instance..method1..method2..methodN

instance..method1 returns this object.

The same can be rewritten using

main() {
  List list = [];
  list
    ..add(1)
    ..add(2)
    ..add(3)
    ..add(4);
}

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;
THE BEST NEWSLETTER ANYWHERE
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
Subscribe
You'll get a notification every time a post gets published here.





Related posts

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

Perl How to: Find a Given Variable String is numeric or not

Dart/Flutter: Check if String is Empty, Null, or Blank example

How to generate Unique Id UUID in Dart or Flutter Programming| Dart or Flutterby Example

How to Sort List of numbers or String in ascending and descending in Dart or Flutter example

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

Dart Example - Program to check Leap year or not