o7planning

Dart dot dot ( .. ) operator

View more Tutorials:

Follow us on our fanpages to receive notifications every time there are new articles. Facebook Twitter

1- Dot dot ( .. ) operator

In the Dart programming language, the dot dot ( .. ) operator is also interpreted as "cascade notation". It allows you to not repeat the same target if you want to call several methods on the same object.
Example:
dotdot_ex1.dart

void main() {
  var list1 = [];
  list1..add('One')..add('Two')..add('Three');
  print(list1); // [One, Two, Three]

  // Same as:
  var list2 = [];
  list2.add('One');
  list2.add('Two');
  list2.add('Three');
  print(list2); // [One, Two, Three]
}
Example: Calling multiple methods of the same object, using the dot dot operator makes your code shorter.
dotdot_ex2.dart

void main() {
  var list1 = [];
  list1..add('One')..add('Two')..addAll(['Three', 'Four', 'Five']);
  print(list1); // [One, Two, Three, Four, Five]  

  // Same as:
  var list2 = [];
  list2.add('One');
  list2.add('Two');
  list2.addAll(['Three', 'Four', 'Five']);
  print(list2); // [One, Two, Three, Four, Five]

  // Same as:
  var list3 = []..add('One')..add('Two')..addAll(['Three', 'Four', 'Five']);
  print(list3); // [One, Two, Three, Four, Five]  
}
In languages that do not support the dot dot operator, to call a sequence of methods, the methods must return an object. Such as:
without_dotdot_ex1.dart

class Calculator {
  double _accumulator = 0;

  Calculator(double startValue) {
    _accumulator = startValue;
  }
  Calculator add(double val) {
    _accumulator += val;
    return this; // Return this object.
  }
  Calculator subtract(double val) {
    _accumulator -= val;
    return this; // Return this object.
  }
  double result() {
    return _accumulator;
  }
}
void main() {
    var calc = Calculator(100);
    var result = calc.add(100).subtract(50).subtract(25).result();
    print(result); // 125
}
The dot dot operator helps you call a series of methods that don't necessarily return an object. We rewrite the above example.
with_dotdot_ex1.dart

class Calculator {
  double _accumulator = 0;

  Calculator(double startValue) {
    _accumulator = startValue;
  }
  void add(double val) {
    _accumulator += val;
  }
  void subtract(double val) {
    _accumulator -= val;
  }
  double result() {
    return _accumulator;
  }
}
void main() {
    var calc = Calculator(100);
    calc..add(100)..subtract(50)..subtract(25);
    var result = calc.result();
    print(result); // 125
}

View more Tutorials: