How to use the global variables in Dart
Global variable
In Dart, a global variable is a variable that can be accessed anywhere within the code.
Advantages of a global variable
- It can be accessed by every function or method in the same program.
- Unlike local variables, global variables do not have limited scope.
Disadvantages of a global variable
-
It is difficult to track changes since any method or function can modify them.
-
It does not support Encapsulation. Therefore, resulting in insecure and complex code maintenance.
Code example
The following code shows how to use the global variable in Dart:
// import the globals fileimport 'globals.dart' as globals;void main() {print('Welcome to ${globals.globalVar}');// modify its valueglobals.globalVar= "Dart programming";// display resultprint('${globals.globalVar} is one of my favorite programming languages');}
Code explanation
First, we create a file called globals.dart that holds the global variable. The main purpose of creating a global.dart file is to import all the variables using the single import command. Moreover, we don’t have to declare it in all the files where we want to use it.
In the globals.dart file, We declare a global variable called globalVar and assign a value to it.
Then, in the main.dart file:
-
Line 2: We import the
globals.dartfile asglobal. This will give us access to the global variable declared in the file. -
Line 4: We define the
main()function. -
Line 5: We used the
print()function to display theglobals.globalVarvalue. -
Line 7: We modify the value for
globals.globalVar. -
Line 9: We display the value using the
print()function.
Free Resources