🦋Flutter - Access global non-changing variables
Luciano Jung
Posted on March 15, 2021
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.
Posted on March 15, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.