🦋Flutter - Singleton Pattern
Luciano Jung
Posted on March 22, 2021
The Singleton pattern is a frequently used pattern in object-oriented programming languages. It is one of the most frequently used programming patterns.
In this post I will show you when the Singleton Pattern is useful for you and how you can integrate it into your Flutter project.
The purpose
The Singleton pattern makes it in object-oriented programming languages possible to use an object of a class in different contexts, without passing it on with function calls constantly. Inversely said it prevents the creation of several objects of a class.
The Singleton Pattern is used to control the object creation and usage of a class dynamically at runtime. It is mostly used when tasks are used frequently and in different parts of an application.
The implementation
Following the Singleton pattern, a class 'MySingletonClass' should manage an object '_instance' and return this object instance when it is created. This is implemented as follows:
class MySingletonClass {
static final MySingletonClass _instance =
MySingletonClass ._internal();
// passes the instantiation to the _instance object
factory MySingletonClass() => _instance;
}
The _internal method can be used to initialize variables:
class MySingletonClass {
[...]
//initialize variables in here
MySingletonClass._internal() {
//_myVariable has to be defined before
_myVariable = 0;
}
}
The singleton-class is now finished and can be implemented. To use it in an existing widget, we get the instance object of the class just as we would create a new instance. This is usually done within a 'State<>' object:
class _MyHomePageState extends State<MyHomePage> {
MySingletonClass _mySingletonClass = MySingletonClass();
[...]
}
Comments
Even if the Singleton pattern seems to be useful, it should not be applied everywhere, otherwise the program code can become dirty and become more like procedurally generated code.
Thanks for reading. If you have any comments or questions, feel free to leave a comment.
Feel free to follow my profile if you want to learn more practical tips about Flutter.
Also feel free to visit my Github profile to learn more about my current OpenSource projects.
🥳Thanks for over 1000 readers!🎉
Buy me a sushi roll if you like to support this kind of content.
You may also like
Posted on March 22, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.