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

  1. It can be accessed by every function or method in the same program.
  2. Unlike local variables, global variables do not have limited scope.

Disadvantages of a global variable

  1. It is difficult to track changes since any method or function can modify them.

  2. 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:

main.dart
globals.dart
// import the globals file
import 'globals.dart' as globals;
void main() {
print('Welcome to ${globals.globalVar}');
// modify its value
globals.globalVar= "Dart programming";
// display result
print('${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.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.

New on Educative
Learn to Code
Learn any Language as a beginner
Develop a human edge in an AI powered world and learn to code with AI from our beginner friendly catalog
🏆 Leaderboard
Daily Coding Challenge
Solve a new coding challenge every day and climb the leaderboard

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved