What is a Variable?
A variable is a named storage location in memory that holds a value. Think of it as a labelled box where you can store data. In Dart, every variable has a type that determines what kind of data it can store.
Declaring Variables
You can declare a variable with an explicit type or using var:
// Explicit type declaration
String name = 'Alice';
int age = 25;
double salary = 55000.50;
bool isEmployed = true;
// Using var (type is inferred)
var city = 'Phnom Penh'; // inferred as String
var count = 10; // inferred as int
Once a variable is declared with var, its type is fixed at compile time and cannot change.
The var Keyword
The var keyword lets Dart infer the type from the value:
var x = 42; // int
var pi = 3.14; // double
var msg = 'Hello'; // String
var flag = true; // bool
// x = 'text'; ← ERROR: can't assign String to int
The dynamic Type
Use dynamic when a variable can hold values of different types at runtime. Avoid it unless necessary — it disables type checking.
dynamic value = 'Hello';
print(value); // Hello
value = 42;
print(value); // 42
value = true;
print(value); // true
Naming Rules
- Must start with a letter or underscore (
_).
- Can contain letters, digits, and underscores.
- Cannot be a Dart keyword.
- Use camelCase by convention:
firstName, totalPrice.
- Private variables (library-scoped) start with
_: _count.
Example
void main() {
String firstName = 'John';
String lastName = 'Doe';
int age = 30;
double height = 5.9;
bool isDeveloper = true;
print('Name: $firstName $lastName');
print('Age: $age');
print('Height: $height ft');
print('Developer: $isDeveloper');
// Reassigning a variable
age = 31;
print('Next year age: $age');
}
Output:
Name: John Doe
Age: 30
Height: 5.9 ft
Developer: true
Next year age: 31
⚠️ Common Mistakes
- Using a variable before declaring it:
print(x); before var x = 5; causes an error.
- Assigning a wrong type:
int age = 'twenty'; is a type error.
- Starting a variable name with a digit:
var 1name = 'x'; is invalid.
💪 Exercise
- Create variables to store your name, age, city, and GPA.
- Print all values in a formatted message.
- Try using
var and let Dart infer the types.
🧠 Quiz
1. What keyword lets Dart infer the type of a variable?
- A) auto
- B) let
- C) var ✅
- D) type
2. Which naming convention does Dart use for variables?
- A) snake_case
- B) PascalCase
- C) camelCase ✅
- D) UPPER_CASE
Summary
Variables store data in named memory locations. In Dart, declare variables with an explicit type (String, int) or use var for type inference. Use dynamic only when the type changes at runtime. Follow camelCase naming conventions.