DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 963,673 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
Cover image for πŸ¦‹Flutter - Singleton Pattern
Luciano Jung
Luciano Jung

Posted on • Updated on

πŸ¦‹Flutter - Singleton Pattern

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;

}
Enter fullscreen mode Exit fullscreen mode

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;
  }
}
Enter fullscreen mode Exit fullscreen mode

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();

  [...]
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)

DEV has this feature:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. πŸ›