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.
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;
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 pairsFor more information on these types, refer to the Dart Data Types guide.
When naming variables in Dart, follow these best practices:
firstName
)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
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.
Dart provides two ways to declare constants:
final
: For runtime constantsconst
: For compile-time constantsfinal pi = 3.14159;
const gravity = 9.8;
Learn more about constants in the Dart Constants guide.
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);
}
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.