In Dart, a global variable is a variable that can be accessed anywhere within the code.
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.
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');}
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.dart
file as global
. 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 the globals.globalVar
value.
Line 7: We modify the value for globals.globalVar
.
Line 9: We display the value using the print()
function.
Free Resources