Dart Singleton Pattern
In this tutorial we will learn what singleton is, when to use singleton pattern and how to implement singleton in Dart.
Singleton is a design pattern and is one of the simplest ones. It is useful in the cases when we want only a single instance of any object in our application. In this tutorial we will learn about the singleton pattern in Dart and how we can create a singletons in Dart. So let’s get started
Create a class and then follow the steps to make it a singleton pattern.
Singleton._internal() {}
Create a private static instance variable, that keeps track of the sole instance.
static Singleton _instance;
Finally, create a static getter method, that allows access of the instance globally. It is responsible to create the new instance if it’s not previously created.
static Singleton get instance {
if(_instance == null) {
_instance = Singleton._internal();
}
return _instance;
}
class Singleton {
String name;
static Singleton _instance;
Singleton._internal() {
name="Singleton pattern";
}
static Singleton get instance {
if(_instance == null) {
_instance = Singleton._internal();
}
return _instance;
}
}
#dart #flutter #mobile-apps #programming #developer