Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dart Singletons
// (!) This implementation seems to work;
// Trying this in DartPad results in "s = false" and "f = true" as expected.
// This was taken from https://gist.github.com/theburningmonk/6401183
class FooBar {
static final FooBar _instance = new FooBar._internal();
factory FooBar() => _instance;
FooBar._internal() {
// initialization logic here
}
}
class SpamEggs {}
void main() {
var s1 = SpamEggs();
var s2 = SpamEggs();
var f1 = FooBar();
var f2 = FooBar();
print('s = ${identical(s1, s2)}');
print('f = ${identical(f1, f2)}');
}
// (!) This singleton implementation doesn't seem to work;
// Trying this in DartPad results in "s = false" and "f = false" which is unexpected.
class FooBar {
static final FooBar _instance = FooBar.getInstance();
FooBar.getInstance();
factory FooBar() => _instance;
}
class SpamEggs {}
void main() {
var s1 = SpamEggs();
var s2 = SpamEggs();
var f1 = FooBar.getInstance();
var f2 = FooBar.getInstance();
print('s = ${identical(s1, s2)}');
print('f = ${identical(f1, f2)}');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment