Skip to content

Instantly share code, notes, and snippets.

@psygo
Created May 6, 2020 02:17
Show Gist options
  • Save psygo/18ba2723dd3ccdbd5817b4ca8eeb0b5b to your computer and use it in GitHub Desktop.
Save psygo/18ba2723dd3ccdbd5817b4ca8eeb0b5b to your computer and use it in GitHub Desktop.
An Example of Const Factories in Dart
// `const factory` basically only redirects the construction of the object.
// A `const` redirecting constructor must redirect to a `const` constructor.
main() {
const A a1 = A('hello');
print(a1);
const A a2 = A.redirected2('hello');
print(a2);
final A a3 = A('hello');
A a4 = A('hello');
print(identical(a1, a2)); // true
print(identical(a1, a3)); // false
print(identical(a1, a4)); // false
}
class A {
final String testField;
const factory A.redirected(String testField) = A;
const factory A.redirected2(String testField) = A._;
const A(this.testField); // should be `const`
const A._(this.testField); // should be `const`
String toString() => this.testField;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment