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?