How to Declare a Variable in Dart

In Dart, declaring a variable is straightforward and can be done using three keywords: var, final, and const. Each of these keywords serves a different purpose and has specific use cases. Below, we will explore how to declare variables using these keywords, along with examples.

1. Using var

The var keyword is used to declare a variable with type inference. This means that the Dart compiler determines the type of the variable based on the assigned value. A variable declared with var can be reassigned to a value of the same type.

void main() {
var name = 'Alice'; // Dart infers the type as String
print('Name: $name');

name = 'Bob'; // Reassigning to another String
print('Updated Name: $name');
}

2. Using final

The final keyword is used to declare a variable that can only be assigned once. Once a value is assigned to a final variable, it cannot be changed. This is useful for constants that are determined at runtime.

void main() {
final age = 30; // Dart infers the type as int
print('Age: $age');

// Uncommenting the next line will cause an error
// age = 31; // Error: The final variable 'age' can only be set once
}

3. Using const

The const keyword is used to declare compile-time constants. A variable declared with const must be assigned a value that is known at compile time, and it cannot be changed. This is useful for defining constants that are used throughout your application.

void main() {
const pi = 3.14; // Compile-time constant
print('Value of Pi: $pi');

// Uncommenting the next line will cause an error
// pi = 3.14159; // Error: Constant variables can't be assigned a value
}

4. Type Annotations

While Dart supports type inference, you can also explicitly specify the type of a variable. This can improve code readability and help catch errors at compile time.

void main() {
String city = 'New York'; // Explicitly specifying the type
int year = 2023; // Explicitly specifying the type

print('City: $city');
print('Year: $year');
}

Conclusion

Declaring variables in Dart is flexible and straightforward. You can use var for type inference, final for single assignment, and const for compile-time constants. Understanding how to declare and use variables effectively is essential for writing clean and efficient Dart code.