Arkay
Arkay

Reputation: 469

Global Variables in Dart: Singleton versus Static

When you want to define global variables in Dart to be read and written anywhere within your program, the general advice seems to be create a Singleton class, e.g.

class Globals {
    // Constructor boilerplate
    static final Globals _instance = Globals._();
    factory Globals() => _instance;
    Globals._();

    // Global variable
    int variable = 0;
}

You can then read the value using Globals().variable and write using Globals().variable = 1.

However the same seems to be possible with a simple static variable, e.g.

class Globals {
    // Global variable
    static int variable = 0;
}

Which are read and written using Globals.variable and Globals.variable = 1. If we run a simple example:

void main() {
   print(Globals.variable);
   Globals.variable++;
   print(Globals.variable);
}

It returns

0
1

And so seems to be functioning as a global variable. I'm using globals in the context of Flutter, where I want a collection of variables to be widely available and adjustable throughout the app.

So what is the difference between declaring globals using singletons and statics?

Upvotes: 3

Views: 2489

Answers (1)

nvoigt
nvoigt

Reputation: 77285

Globals are not good programming, someone should have taught that in the basic course and Singleton is not much better. It's just a fancier way of declaring globals. See Why is Singleton considered an anti-pattern?.

So the literal answer to your question is "nothing of importance". Global variables and Singletons are basically the same, with the same problems.

The actual answer to such a question should be use neither!!!

If you don't know how to manage your programs state without it, go read up on state management in Flutter.

Upvotes: 3

Related Questions