Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the meaning of `Class._()..property`?

Tags:

flutter

dart

What does ._().. mean in the following code?

class CounterState {
  int counter;

  CounterState._();

  factory CounterState.init() {
    return CounterState._()..counter = 0;
  }
}

More precisely - what do the two dots .. mean past ._()?

like image 998
Makarenkov Oleg Avatar asked Dec 24 '19 09:12

Makarenkov Oleg


2 Answers

Cascade notation (..)

In the Dart Languague tour, which you should really check out because it contains a lot of useful information, you can also find information about the cascade notation you mentioned:

Cascades (..) allow you to make a sequence of operations on the same object. In addition to function calls, you can also access fields on that same object. This often saves you the step of creating a temporary variable and allows you to write more fluid code.

As an example, if you want to update multiple fields of your render object, you can simply use the cascade notation to save some characters:

renderObject..color = Colors.blue
    ..position = Offset(x, y)
    ..text = greetingText
    ..listenable = animation;

// The above is the same as the following:
renderObject.color = Colors.blue;
renderObject.position = Offset(x, y);
renderObject.text = greetingText;
renderObject.listenable = animation;

It also helps when you want to return an object in the same line as assigning a value or calling a function:

canvas.drawPaint(Paint()..color = Colors.amberAccent);

Named constructors

._() is a named private constructor. If a class does not specify another constructor (either default or named) that is not private, that class cannot be instantiated from outside of the library.

class Foo {
  Foo._(); // Cannot be called from outside of this file.

  // Foo(); <- If this was added, the class could be instantiated, even if the private named constructor exists.
}

Learn more about private constructors.

like image 62
creativecreatorormaybenot Avatar answered Nov 10 '22 01:11

creativecreatorormaybenot


.. This called cascade-notation

Cascades (..) allow you to make a sequence of operations on the same object.

In addition to function calls, you can also access fields on that same object. This often saves you the step of creating a temporary variable and allows you to write more fluid code.

Example

querySelector('#confirm') // Get an object.
  ..text = 'Confirm' // Use its members.
  ..classes.add('important')
  ..onClick.listen((e) => window.alert('Confirmed!'));
like image 21
Ravinder Kumar Avatar answered Nov 10 '22 03:11

Ravinder Kumar