June 2017
Intermediate to advanced
873 pages
18h 9m
English
In some cases, you only need one unique instance of a class because this is simply enough for the app you're working with, or perhaps to save resources. This recipe shows you how to do this in Dart.
The singleton example shows how to do this (substitute your singleton class name for Immortal). Use a factory constructor to implement the singleton pattern, as shown in the following code:
class Immortal {
static final Immortal theOne = new Immortal._internal('Connor MacLeod');
String name;
factory Immortal(name) => theOne;
// private, named constructor
Immortal._internal(this.name); } main() { var im1 = new Immortal('Juan Ramirez'); var im2 = new Immortal('The Kurgan'); print(im1.name); // Connor MacLeod print(im2.name); ...Read now
Unlock full access