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 ._()
?
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);
._()
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.
..
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!'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With