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:
1. var p1 = Point(2, 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:
1. var p1 = new Point(2, 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:
1. var p = const ImmutablePoint(2, 2);
Constructing two identical compile-time constants results in a single,canonical instance:
1. var a = const ImmutablePoint(1, 1);
2. var b = const ImmutablePoint(1, 1);
4. 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:
1. // Lots of const keywords here.
2. const pointAndLine = const {
3. 'point': const [const ImmutablePoint(0, 0)],
4. 'line': const [const ImmutablePoint(1, 10), const ImmutablePoint(-2, 11)],
5. };
You can omit all but the first use of the const keyword:
1. // Only one const, which establishes the constant context.
2. const pointAndLine = {
3. 'point': [ImmutablePoint(0, 0)],
4. 'line': [ImmutablePoint(1, 10), ImmutablePoint(-2, 11)],
5. };
If a constant constructor is outside of a constant contextand is invoked without const,it creates a non-constant object:
1. var a = const ImmutablePoint(1, 1); // Creates a constant
2. var b = ImmutablePoint(1, 1); // Does NOT create a constant
4. assert(!identical(a, b)); // NOT the same instance!
Version note: The const keyword became optional within a constant context in Dart 2.
