Skip to content

Instantly share code, notes, and snippets.

@yakubpashask
Created April 9, 2020 17:54
Show Gist options
  • Save yakubpashask/a3bf913860e3ced8111b215d58705903 to your computer and use it in GitHub Desktop.
Save yakubpashask/a3bf913860e3ced8111b215d58705903 to your computer and use it in GitHub Desktop.
Different Ways of Create Singleton classes in dart
//1. Factory constructor
class SingletonOne {
SingletonOne._privateConstructor();
static final SingletonOne _instance = SingletonOne._privateConstructor();
factory SingletonOne() {
return _instance;
}
}
//Static field with getter
class SingletonTwo {
SingletonTwo._privateConstructor();
static final SingletonTwo _instance = SingletonTwo._privateConstructor();
static SingletonTwo get instance => _instance;
}
//3. Static field
class SingletonThree {
SingletonThree._privateConstructor();
static final SingletonThree instance = SingletonThree._privateConstructor();
}
//ways of init
SingletonOne one = SingletonOne();
SingletonTwo two = SingletonTwo.instance;
SingletonThree three = SingletonThree.instance;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment