Dart Variables
Learn Dart through interactive, bite-sized lessons. Build Flutter apps and master modern development.
Start Dart Journey →Variables are fundamental building blocks in Dart programming. They serve as containers for storing and manipulating data within your code. Understanding how to declare, initialize, and use variables is crucial for effective Dart development.
Declaring Variables
In Dart, you can declare variables using various approaches. The most common method is to use the var keyword, which allows Dart to infer the variable's type:
var name = 'John Doe';
var age = 30;
var height = 1.75;
Alternatively, you can explicitly specify the variable type:
String country = 'Canada';
int population = 38000000;
double gdp = 1.643;
Variable Types
Dart supports several built-in data types, including:
int: For whole numbersdouble: For floating-point numbersString: For textbool: For true/false valuesList: For ordered collections of objectsMap: For key-value pairs
For more information on these types, refer to the Dart Data Types guide.
Variable Naming Conventions
When naming variables in Dart, follow these best practices:
- Use camelCase for variable names (e.g.,
firstName) - Start with a lowercase letter
- Avoid using reserved keywords
- Choose descriptive names that reflect the variable's purpose
Variable Scope
Variables in Dart have different scopes depending on where they are declared. Local variables are confined to the block they're defined in, while top-level variables are accessible throughout the entire file.
void main() {
var localVar = 'I am local';
print(localVar); // Accessible
}
// Outside the main function
print(localVar); // Error: localVar is not defined in this scope
Null Safety
Dart 2.12 introduced null safety, a powerful feature that helps prevent null reference errors. With null safety, variables must be explicitly declared as nullable using the ? operator:
String? nullableString = null; // OK
String nonNullableString = 'Hello'; // OK
String nonNullableString = null; // Error
For more details on null safety, check out the Dart Null Safety guide.
Constants
Dart provides two ways to declare constants:
final: For runtime constantsconst: For compile-time constants
final pi = 3.14159;
const gravity = 9.8;
Learn more about constants in the Dart Constants guide.
Late Variables
The late keyword allows you to declare non-nullable variables that are initialized after their declaration:
late String lateInitialized;
void someFunction() {
lateInitialized = 'Now initialized';
print(lateInitialized);
}
Conclusion
Understanding variables is crucial for mastering Dart programming. They form the foundation for data manipulation and storage in your applications. As you progress, explore more advanced concepts like Dart Operators and Dart Function Basics to enhance your Dart programming skills.