In Flutter, you often have non-changing values that are used across the app (for example the app name, version, etc.) Wouldn't it be nice for you to have globally managed access for these?
Of course and I'll show you how to do it here:
The basic idea
For the simple administration of global values it is sufficient to have a static access to a class, which provides the needed values. For this it is recommended to use the Singleton pattern in this class.
The solution
To solve this problem we generate a class (I call it Globalvariables for this example). In this we implement the singleton pattern as shown below.
class GlobalVariables{
static final GlobalVariables _instance = GlobalVariables._internal();
factory GlobalVariables() => _instance;
GlobalVariables._internal();
[...]
}
Then we create the getter functions without declaring variables.
class GlobalVariables{
[...]
String get name => 'My Flutter App';
String get version => '1.0.0';
int get versionCode => 100;
}
We can now access these Variables with the following line of code:
GlobalVariables().name // => My Flutter App
Comments
Instead of using the Singleton pattern, it is of course also possible, but less convenient, to define static variables or functions with the addition 'static':
static String get name => 'My Flutter App';
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.
Top comments (1)
I would say the opposite: that a static variable is by far the simpler route. It does not require the programming of a single-instance object factory constructor--nor the "creation" of this
new GlobalVariables()
on each retrieval, which may ultimately look tacky and less readable anyway. In fact, in your singleton solution, you employ thestatic
concept already: in the assignment of your singleton_instance
to the private constructor.I usually opt to create an abstract class with a single constructor that is private (such that a default, nameless, no-parameter constructor is not automatically generated by Dart, especially in the case of
dartdoc
documentation). This class hasstatic const
fields accessible from anywhere the abstract class is imported by simply callingGlobalVariables.desiredVariable
.As a further profit from this proposed solution, these variables are constant, as per
const
. If utilized in an application, the value of the field is stored in memory just once and retrieved when needed. This is directly in opposition to a getter as per yourString get name => 'My Flutter App'
solution.