On this page28 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. What Is a Variable?
- 2. Declaring a Variable
- 3. Declare Now, Assign Later — Only Inside a Function
- 4. Initializing a Variable
- 5. Assignment
- 6. Using Variables in print()
- 7. String Interpolation
- 8. Variables in Calculations
- 9. Changing a Variable
- 10. Variable Types
- 11. A Whole Number in a double
- 12. Type Safety
- 13. Naming Rules
- 14. Naming Conventions: Good Names vs Poor Names
- 15. Variables and Program Flow
- 16. A Real-World Example
- Code Examples
- Common Beginner Mistakes
- Best Practices
- Mini Challenge
- Practice Questions
- Practice Answers
- Quick Revision
- Key Takeaways
- What's Next?
Lecture 04 — Variables in Dart
| Category | 2 — Variables & Data Types |
| Lecture | 004 of 140 |
| Estimated video length | 9 min |
| Target | Dart 3.12.2 |
| Level | Beginner |
Until now we printed values directly. A variable gives a value a name, so the program can store it once and reuse it anywhere.
Contents
Prerequisites · Connection · Objectives · Lesson · Code Examples · Common Mistakes · Best Practices · Mini Challenge · Practice Questions · Answers · Takeaways
Every error message in this lecture is real. Each one was produced by running the code shown on Dart 3.12.2, so you will recognize it when you meet it yourself.
Prerequisites
Students should already understand, from Lectures 001–003:
- the basic structure of a Dart program
main()andprint()- statements, strings, and numbers
- comments
Connection With Previous Lectures
Until now, we mostly printed values directly:
print('Ali');This displays a value, but we cannot easily reuse that value later. If the same name had to appear in five messages, we would type it five times — and change it in five places when it changed. Variables solve this problem by giving us a named place to store a value.
Learning Objectives
By the end of this lecture you will be able to:
- Understand what a variable is
- Understand declaration, initialization, and assignment
- Create variables using explicit types
- Read and change variable values
- Understand how variables make programs reusable
- Use variables with
print()and in calculations - Apply Dart's naming rules and naming conventions
- Recognize the error messages Dart produces for common variable mistakes
1. What Is a Variable?
A variable is a name that refers to a stored value the program can work with.
Analogy — think of a labeled box. The label is the variable's name, and the value is whatever is currently inside the box. You can look inside the box by name, and (for most variables) you can put something new in it later.
String name = 'Ali';
int age = 20;Here name refers to the text 'Ali', and age refers to the number 20.
2. Declaring a Variable
A declaration introduces a variable to the program: it states the variable's type and its name.
String name;This tells Dart that name is a String variable. We have declared it, but we have not
supplied a value yet — and Dart cares a great deal about that. The next section explains
exactly when this is allowed.
3. Declare Now, Assign Later — Only Inside a Function
A String is a non-nullable type: it is not allowed to hold "no value". So Dart insists
that a variable holds a real value before anyone reads it.
Inside a function this is fine, as long as you assign before you read:
void main() {
String name;
name = 'Ali';
print(name);
}AliReading it before assigning is an error:
void main() {
String name;
print(name);
}Error: Non-nullable variable 'name' must be assigned before it can be used.
print(name);
^^^^Outside a function, declaring without a value is always an error. A variable written at
the top of the file — outside main() — must be given its value right there:
String name; // ✗ not allowed at the top level
void main() {
name = 'Ali';
print(name);
}Error: Field 'name' should be initialized because its type 'String' doesn't allow null.
String name;
^^^^The fix is simply to initialize it where it is declared:
String name = 'Ali'; // ✓ fine
void main() {
print(name);
}AliRule of thumb for now: declare your variables inside
main()and give them a value straight away. That is what the rest of this lecture does.
4. Initializing a Variable
Initialization means giving a variable its initial value.
String name = 'Ali';
int age = 20;Declaration and initialization commonly happen together, on one line. This is the style you should prefer.
5. Assignment
Assignment means giving a variable a value. A variable declared with an explicit
non-final type can be assigned a new value of a compatible type.
void main() {
int age = 20;
age = 21;
print(age);
}21The first line gives age the value 20. The second assignment changes it to 21.
6. Using Variables in print()
void main() {
String name = 'Zayan';
int age = 6;
print(name);
print(age);
}Zayan
6Variables let us store information once and use it in multiple places.
7. String Interpolation
Dart can insert a variable's value into a string using $. For a simple variable, write
$variableName.
void main() {
String name = 'Ali';
int age = 20;
print('Name: $name');
print('Age: $age');
}Name: Ali
Age: 20This makes output much easier to read than joining pieces by hand. We will study string interpolation in greater depth when we cover Strings (Lecture 008).
8. Variables in Calculations
void main() {
int price = 100;
int quantity = 3;
print(price * quantity);
}300Instead of putting bare numbers into the calculation, we give them meaningful names. This makes the program easier to understand and easier to change.
9. Changing a Variable
void main() {
int score = 10;
print(score);
score = 20;
print(score);
}10
20A normal mutable variable can hold a different value later, provided the new value is compatible with its type.
10. Variable Types
Dart supports many types. At this stage, focus on these four:
| Type | Stores | Example |
|---|---|---|
String | text | 'Sara' |
int | whole numbers | 18 |
double | decimal numbers | 99.5 |
bool | true or false | true |
void main() {
String name = 'Sara';
int age = 18;
double price = 99.5;
bool isStudent = true;
print(name);
print(age);
print(price);
print(isStudent);
}Sara
18
99.5
true11. A Whole Number in a double
You may write a whole number where a double is expected. Dart accepts it and stores it as a
decimal value:
void main() {
double temperature = 25; // written as 25, stored as 25.0
print(temperature);
}25.0This surprises many beginners: the program prints 25.0, not 25. A double always shows
its decimal part, even when that part is zero. Nothing is wrong — the value simply is a
decimal number.
12. Type Safety
An explicitly typed variable is expected to contain values of that type.
void main() {
int age = 20;
age = 21; // ✓ both values are integers
print(age);
}21Assigning a different type is rejected before the program even runs:
void main() {
int age = 20;
age = 'twenty'; // ✗
print(age);
}Error: A value of type 'String' can't be assigned to a variable of type 'int'.
age = 'twenty';
^Dart's type system catches incompatible values for you, at compile time, instead of letting the program misbehave while it is running.
13. Naming Rules
These are rules — break one and the program will not compile.
| Rule | ✗ Invalid | ✓ Valid |
|---|---|---|
| Must not start with a digit | 1stPlace | firstPlace |
| Must not contain spaces | student age | studentAge |
| Must not be a Dart keyword | class, if, void | className |
| Names are case-sensitive | Name ≠ name | pick one and stay consistent |
A keyword used as a name produces a very clear message:
void main() {
int class = 1; // ✗
print(class);
}Error: 'class' can't be used as an identifier because it's a keyword.
Try renaming this to be an identifier that isn't a keyword.
int class = 1;
^^^^^Case sensitivity causes one of the most common beginner bugs. name and Name are two
completely different names, so this fails:
void main() {
String name = 'Ali';
print(Name); // ✗ capital N
}Error: Undefined name 'Name'.
print(Name);
^^^^Dart is not guessing what you meant — it simply has no variable called Name.
14. Naming Conventions: Good Names vs Poor Names
Rules decide what compiles. Conventions decide what is easy to read. For Dart variables, the convention is lowerCamelCase: start lowercase, capitalize each following word.
int studentAge = 20;
double productPrice = 250.0;
String studentName = 'Ali';Compare:
// Less clear
int x = 20;
// Clearer
int studentAge = 20;Both compile, but studentAge communicates meaning immediately. Prefer names that explain
what the value represents.
15. Variables and Program Flow
void main() {
int balance = 1000;
print('Starting balance: $balance');
balance = balance - 250;
print('After purchase: $balance');
}Starting balance: 1000
After purchase: 750A variable can be read, used in an expression, and then updated. Note balance = balance - 250:
the right-hand side is calculated first using the old value, and the result then becomes
the new value.
16. A Real-World Example
void main() {
String productName = 'Notebook';
int price = 500;
int quantity = 2;
int total = price * quantity;
print('Product: $productName');
print('Total: $total');
}Product: Notebook
Total: 1000This is the important idea: store information in meaningful variables, process it, then use the result.
Code Examples
Example 1 — Basic Variables
void main() {
String name = 'Ali';
int age = 20;
print(name);
print(age);
}Ali
20Example 2 — Different Types
void main() {
String name = 'Sara';
int age = 18;
double height = 5.6;
bool isStudent = true;
print(name);
print(age);
print(height);
print(isStudent);
}Sara
18
5.6
trueExample 3 — Interpolation
void main() {
String name = 'Zayan';
int age = 6;
print('Name: $name');
print('Age: $age');
}Name: Zayan
Age: 6Example 4 — Updating a Value
void main() {
int score = 50;
print(score);
score = 75;
print(score);
}50
75Example 5 — Calculation
void main() {
int price = 200;
int quantity = 4;
int total = price * quantity;
print(total);
}800Example 6 — Multiple Updates
void main() {
int balance = 1000;
balance = balance - 200;
balance = balance + 50;
print(balance);
}850How it works
balancestarts at1000.balance - 200is calculated as800, and that result replaces the old value.balance + 50is calculated as850, and that result replaces the value again.- Only the final value,
850, is printed.
Example 7 — Student Information
void main() {
String name = 'Zayan';
int age = 6;
String grade = '1';
print('Name: $name');
print('Age: $age');
print('Grade: $grade');
}Name: Zayan
Age: 6
Grade: 1How it works
- Three variables hold three separate pieces of the same record.
gradeis aString, not anint, because a grade is a label rather than a number we calculate with.- Each
printbuilds a readable line using interpolation.
Example 8 — Shopping Total
void main() {
String product = 'Notebook';
int price = 500;
int quantity = 3;
int total = price * quantity;
print('Product: $product');
print('Price: $price');
print('Quantity: $quantity');
print('Total: $total');
}Product: Notebook
Price: 500
Quantity: 3
Total: 1500How it works
priceandquantityhold the inputs.totalis a new variable holding a calculated result —500 * 3, which is1500.- Because
priceandquantityare bothint, their product is also anint. - Changing
quantityto5would update the total automatically; nothing else needs editing.
Example 9 — Temperature Conversion
void main() {
double celsius = 25;
double fahrenheit = (celsius * 9 / 5) + 32;
print('Celsius: $celsius');
print('Fahrenheit: $fahrenheit');
}Celsius: 25.0
Fahrenheit: 77.0How it works
celsiusis declareddoublebut written as25— allowed, and stored as25.0(see section 11).- The brackets force the multiplication and division to happen before
+ 32. 25 * 9 / 5is45.0, and45.0 + 32is77.0.- Both values print with a decimal part because both are
double.
Example 10 — Simple Score Update
void main() {
int score = 60;
score = score + 15;
score = score + 10;
print('Final score: $score');
}Final score: 85How it works
scorestarts at60.score = score + 15reads the old value, adds15, and stores75back.- The same pattern adds
10, giving85. - This "read, change, store back" pattern is how a running total works.
Common Beginner Mistakes
1. Reading a variable before it has a value
void main() {
String name;
print(name);
}Error: Non-nullable variable 'name' must be assigned before it can be used.Assign a value before you read it — ideally on the declaration line.
2. Assigning the wrong type
void main() {
int age = 20;
age = 'twenty';
}Error: A value of type 'String' can't be assigned to a variable of type 'int'.3. Getting the capital letters wrong
void main() {
String name = 'Ali';
print(Name);
}Error: Undefined name 'Name'.name and Name are different variables. Dart will not guess.
4. Declaring a top-level variable without a value
String name;Error: Field 'name' should be initialized because its type 'String' doesn't allow null.Outside a function, a non-nullable variable must be initialized where it is declared.
5. Confusing = with equality
The = operator assigns a value. Equality comparisons will be introduced later.
6. Accidentally replacing a value instead of updating it
score = 100 replaces the previous value. To add to it, you must read the old value
first: score = score + 100.
7. Using unclear names
Names such as x and y may be confusing when a meaningful name such as studentAge
would be clearer.
Best Practices
- Use descriptive lowerCamelCase names.
- Declare and initialize on the same line whenever you can.
- Give variables a type when explicit typing improves clarity; otherwise learn to use type inference appropriately in the next lecture.
- Keep variable scope as small as practical.
- Do not create variables that are never used.
- Choose names based on meaning, not shortness.
- Keep related calculations close to the variables they use.
Mini Challenge
Create a small program for a student report. Store the student's name ('Ali') and three
subject marks — math 80, science 75, English 85. Calculate the total and print the
student's name and total.
Your program should print exactly:
Student: Ali
Total: 240Try it yourself before opening the solution.
Show solution
void main() {
String name = 'Ali';
int math = 80;
int science = 75;
int english = 85;
int total = math + science + english;
print('Student: $name');
print('Total: $total');
}Student: Ali
Total: 240How it works
- Four variables hold the inputs: one name and three marks.
totalis calculated from the three marks:80 + 75 + 85.- The two
printlines report the name and the calculated result.
Practice Questions
Work through these in order — they run from beginner to application to challenge. Every question gives you exact values, so you can compare your output with the answers.
Beginner
- Create a
Stringvariable namedcityholding'Lahore'and print it. - Create
intvariablesage = 20andyear = 2026, then print both, each on its own line. - Create a
doublevariableprice = 99.5and aboolvariableinStock = true, then print both.
Application
- Store the name
'Sara'and age18, then print them on one line using string interpolation, in the formName: Sara, Age: 18. - Store
price = 250andquantity = 4, calculate the total cost, and print only the total. - Store
score = 50, print it, change it to80, then print it again. - Store three subject marks —
80,75,85— calculate their total, and print only the total. - Store a rectangle's
width = 12.5andheight = 4, calculate the area, and print it.
Challenge
- Store
first = 'Ali'andsecond = 'Sara'. Swap their values so thatfirstholds'Sara'andsecondholds'Ali', then print them asFirst: …andSecond: …. Hint: you will need a third variable to hold one value temporarily. - Write a receipt program. Store
price = 1200,quantity = 3, anddiscountRate = 0.10. Calculate the subtotal, the discount amount, and the final total, then print all three labelled asSubtotal:,Discount:, andTotal:.
Practice Answers
Question 1 — Solution
void main() {
String city = 'Lahore';
print(city);
}LahoreQuestion 2 — Solution
void main() {
int age = 20;
int year = 2026;
print(age);
print(year);
}20
2026Question 3 — Solution
void main() {
double price = 99.5;
bool inStock = true;
print(price);
print(inStock);
}99.5
trueQuestion 4 — Solution
void main() {
String name = 'Sara';
int age = 18;
print('Name: $name, Age: $age');
}Name: Sara, Age: 18Question 5 — Solution
void main() {
int price = 250;
int quantity = 4;
int total = price * quantity;
print(total);
}1000Question 6 — Solution
void main() {
int score = 50;
print(score);
score = 80;
print(score);
}50
80Question 7 — Solution
void main() {
int math = 80;
int science = 75;
int english = 85;
int total = math + science + english;
print(total);
}240Question 8 — Solution
void main() {
double width = 12.5;
double height = 4;
double area = width * height;
print(area);
}50.0height is written as 4 but stored as 4.0, so the area prints as 50.0.
Question 9 — Solution
void main() {
String first = 'Ali';
String second = 'Sara';
String temp = first; // keep a copy of 'Ali'
first = second; // first now holds 'Sara'
second = temp; // second gets the copy, 'Ali'
print('First: $first');
print('Second: $second');
}First: Sara
Second: AliWithout temp, the first assignment would overwrite 'Ali' and it would be lost forever —
second would end up holding 'Sara' as well.
Question 10 — Solution
void main() {
int price = 1200;
int quantity = 3;
double discountRate = 0.10;
int subtotal = price * quantity;
double discount = subtotal * discountRate;
double total = subtotal - discount;
print('Subtotal: $subtotal');
print('Discount: $discount');
print('Total: $total');
}Subtotal: 3600
Discount: 360.0
Total: 3240.0subtotal is an int because both inputs are int. As soon as the double discountRate
enters the calculation, the result becomes a double — which is why discount and total
print with a decimal part.
Quick Revision
- What is a variable?
- What is the difference between declaring and initializing a variable?
- What does
=do? - Name four common Dart data types.
- How do you put a variable's value inside a string?
- What happens if you read a non-nullable local variable before assigning it?
- Why is
Namenot the same variable asname? - Why does
double price = 25;print25.0?
Key Takeaways
- A variable gives a name to information used by a program.
- Declaration introduces a variable; initialization gives it its initial value.
- A non-nullable variable must hold a value before it is read — and a top-level variable must be initialized where it is declared.
- Assignment can change the value of a mutable variable.
- Dart supports types such as
String,int,double, andbool. - A whole number written into a
doubleis stored and printed as a decimal (25→25.0). - Naming rules decide what compiles; naming conventions (lowerCamelCase) decide what is readable. Names are case-sensitive.
- Dart's type system catches incompatible assignments at compile time.
What's Next?
Lecture 05 — var & Type Inference. Now that you understand explicit variable types, we
will learn how Dart can infer a variable's type automatically using var, when var is
useful, and how type inference still preserves Dart's type safety.