Constructors
DO
DO use initializing formals when possible.
Many fields are initialized directly from a constructor parameter, like:
class Point {
num x, y;
Point(num x, num y) {
this.x = x;
this.y = y;
}
}
We’ve got to type x
four times here to define a field. We can do better:
class Point {
num x, y;
Point(this.x, this.y);
}
This this.
syntax before a constructor parameter is called an “initializing formal”. You can’t always take advantage of it. Sometimes you want to have a named parameter whose name doesn’t match the name of the field you are initializing. But when you can use initializing formals, you should.
DO use ;
instead of {}
for empty constructor bodies.
In Dart, a constructor with an empty body can be terminated with just a semicolon. (In fact, it’s required for const constructors.)
class Point {
int x, y;
Point(this.x, this.y);
}
class Point {
int x, y;
Point(this.x, this.y) {}
};
DON'T
DON’T type annotate initializing formals.
If a constructor parameter is using this.
to initialize a field, then the type of the parameter is understood to be the same type as the field.
class Point {
int x, y;
Point(this.x, this.y);
}
class Point {
int x, y;
Point(int this.x, int this.y);
}
DON’T use new
.
Dart 2 makes the new
keyword optional. Even in Dart 1, its meaning was never clear because factory constructors mean a new
invocation may still not actually return a new object.
The language still permits new
in order to make migration less painful, but consider it deprecated and remove it from your code.
Widget build(BuildContext context) {
return Row(
children: [
RaisedButton(
child: Text('Increment'),
),
Text('Click!'),
],
);
}
Widget build(BuildContext context) {
return new Row(
children: [
new RaisedButton(
child: new Text('Increment'),
),
new Text('Click!'),
],
);
}
DON’T use const
redundantly.
In contexts where an expression must be constant, the const
keyword is implicit, doesn’t need to be written, and shouldn’t. Those contexts are any expression inside:
- A const collection literal.
- A const constructor call
- A metadata annotation.
- The initializer for a const variable declaration.
-
A switch case expression—the part right after
case
before the:
, not the body of the case.
(Default values are not included in this list because future versions of Dart may support non-const default values.)
Basically, any place where it would be an error to write new
instead of const
, Dart 2 allows you to omit the const
.
const primaryColors = [
Color("red", [255, 0, 0]),
Color("green", [0, 255, 0]),
Color("blue", [0, 0, 255]),
];
const primaryColors = const [
const Color("red", const [255, 0, 0]),
const Color("green", const [0, 255, 0]),
const Color("blue", const [0, 0, 255]),
];