Variables in Dart
In Dart, variables can be declared in various ways depending on their intended use. Here’s a detailed explanation of different types of variable declarations with examples:
1. Using `var`
The `var` keyword is used to declare variables without explicitly specifying their type. The type is inferred by the Dart compiler:
void main() {
var name = 'Alice'; // String type inferred
var age = 30; // int type inferred
var isStudent = true; // bool type inferred
print('Name: $name, Age: $age, Is Student: $isStudent');
}
- Using Explicit Types
You can explicitly specify the type of a variable:
void main() {
String name = 'Bob';
int age = 25;
double height = 5.9;
bool isEmployed = true;
print('Name: $name, Age: $age, Height: $height, Is Employed: $isEmployed');
}
- Using `final`
The `final` keyword is used to declare a variable that can be set only once. The value cannot be changed after it is set:
void main() {
final city = 'New York'; // Type inferred as String
// city = 'Los Angeles'; // Error: Cannot change the value of a final variable
final int population = 8000000;
print('City: $city, Population: $population');
}
- Using `const`
The `const` keyword is used to declare compile-time constants. These variables are immutable and their values must be known at compile time:
void main() {
const pi = 3.14; // Type inferred as double
const String greeting = 'Hello, World!';
print('PI: $pi, Greeting: $greeting');
}
- Late Initialization with ‘late’
The `late` keyword is used to declare a variable that will be initialized later, but the type is known:
void main() {
late String description;
description = 'Dart is a client-optimized language for fast apps on any platform.';
print(description);
}
- Using Dynamic Type with `dynamic`
The `dynamic` keyword allows a variable to hold values of any type and the type can change over time:
void main() {
dynamic variable = 'Hello';
print(variable); // Output: Hello
variable = 123;
print(variable); // Output: 123
variable = true;
print(variable); // Output: true
}
- Null Safety
Dart has null safety, which helps avoid null pointer exceptions.
By default, variables cannot be null unless explicitly declared as nullable using the `?` operator:
void main() {
int? age = null; // Nullable integer
print(age); // Output: null
age = 30;
print(age); // Output: 30
}
Summary of Variable Declaration Syntax
- `var` for type inference:
var name = ‘Alice’;
…
- Explicit type:
`String name = ‘Bob’;
“`
- `final` for single-assignment:
final city = ‘New York’;
“`
- `const` for compile-time constants:
const pi = 3.14;
“`
- `late` for late initialization:
late String description;
“`
- `dynamic` for dynamic types:
dynamic variable = ‘Hello’;
“`
- Nullable types:
int? age = null;
…
These different ways of declaring variables allow for flexibility in how you define and use variables in your Dart programs.
