Using constructors
You can create an object using a constructor.Constructor names can be either ClassName
orClassName.identifier
. For example,the following code creates Point
objects using thePoint()
and Point.fromJson()
constructors:
var p1 = Point(2, 2);
var p2 = Point.fromJson({'x': 1, 'y': 2});
The following code has the same effect, butuses the optional new
keyword before the constructor name:
var p1 = new Point(2, 2);
var p2 = new Point.fromJson({'x': 1, 'y': 2});
Version note: The new
keyword became optional in Dart 2.
Some classes provide constant constructors.To create a compile-time constant using a constant constructor,put the const
keyword before the constructor name:
var p = const ImmutablePoint(2, 2);
Constructing two identical compile-time constants results in a single,canonical instance:
var a = const ImmutablePoint(1, 1);
var b = const ImmutablePoint(1, 1);
assert(identical(a, b)); // They are the same instance!
Within a constant context, you can omit the const
before a constructoror literal. For example, look at this code, which creates a const map:
// Lots of const keywords here.
const pointAndLine = const {
'point': const [const ImmutablePoint(0, 0)],
'line': const [const ImmutablePoint(1, 10), const ImmutablePoint(-2, 11)],
};
You can omit all but the first use of the const
keyword:
// Only one const, which establishes the constant context.
const pointAndLine = {
'point': [ImmutablePoint(0, 0)],
'line': [ImmutablePoint(1, 10), ImmutablePoint(-2, 11)],
};
If a constant constructor is outside of a constant contextand is invoked without const
,it creates a non-constant object:
var a = const ImmutablePoint(1, 1); // Creates a constant
var b = ImmutablePoint(1, 1); // Does NOT create a constant
assert(!identical(a, b)); // NOT the same instance!
Version note: The const
keyword became optional within a constant context in Dart 2.