Watch the video (9 min)
On this page28 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. What Is a Variable?
  5. 2. Declaring a Variable
  6. 3. Declare Now, Assign Later — Only Inside a Function
  7. 4. Initializing a Variable
  8. 5. Assignment
  9. 6. Using Variables in print()
  10. 7. String Interpolation
  11. 8. Variables in Calculations
  12. 9. Changing a Variable
  13. 10. Variable Types
  14. 11. A Whole Number in a double
  15. 12. Type Safety
  16. 13. Naming Rules
  17. 14. Naming Conventions: Good Names vs Poor Names
  18. 15. Variables and Program Flow
  19. 16. A Real-World Example
  20. Code Examples
  21. Common Beginner Mistakes
  22. Best Practices
  23. Mini Challenge
  24. Practice Questions
  25. Practice Answers
  26. Quick Revision
  27. Key Takeaways
  28. What's Next?

Lecture 04 — Variables in Dart

Category2 — Variables & Data Types
Lecture004 of 140
Estimated video length9 min
TargetDart 3.12.2
LevelBeginner

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() and print()
  • statements, strings, and numbers
  • comments

Connection With Previous Lectures

Until now, we mostly printed values directly:

dart
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.

dart
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.

dart
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:

dart
void main() {
  String name;
  name = 'Ali';
  print(name);
}
output
Ali

Reading it before assigning is an error:

dart
void main() {
  String name;
  print(name);
}
output
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:

dart
String name; // ✗ not allowed at the top level

void main() {
  name = 'Ali';
  print(name);
}
output
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:

dart
String name = 'Ali'; // ✓ fine

void main() {
  print(name);
}
output
Ali

Rule 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.

dart
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.

dart
void main() {
  int age = 20;
  age = 21;
  print(age);
}
output
21

The first line gives age the value 20. The second assignment changes it to 21.


6. Using Variables in print()

dart
void main() {
  String name = 'Zayan';
  int age = 6;
  print(name);
  print(age);
}
output
Zayan
6

Variables 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.

dart
void main() {
  String name = 'Ali';
  int age = 20;
  print('Name: $name');
  print('Age: $age');
}
output
Name: Ali
Age: 20

This 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

dart
void main() {
  int price = 100;
  int quantity = 3;
  print(price * quantity);
}
output
300

Instead 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

dart
void main() {
  int score = 10;
  print(score);
  score = 20;
  print(score);
}
output
10
20

A 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:

TypeStoresExample
Stringtext'Sara'
intwhole numbers18
doubledecimal numbers99.5
booltrue or falsetrue
dart
void main() {
  String name = 'Sara';
  int age = 18;
  double price = 99.5;
  bool isStudent = true;
  print(name);
  print(age);
  print(price);
  print(isStudent);
}
output
Sara
18
99.5
true

11. 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:

dart
void main() {
  double temperature = 25; // written as 25, stored as 25.0
  print(temperature);
}
output
25.0

This 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.

dart
void main() {
  int age = 20;
  age = 21; // ✓ both values are integers
  print(age);
}
output
21

Assigning a different type is rejected before the program even runs:

dart
void main() {
  int age = 20;
  age = 'twenty'; // ✗
  print(age);
}
output
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 digit1stPlacefirstPlace
Must not contain spacesstudent agestudentAge
Must not be a Dart keywordclass, if, voidclassName
Names are case-sensitiveName ≠ namepick one and stay consistent

A keyword used as a name produces a very clear message:

dart
void main() {
  int class = 1; // ✗
  print(class);
}
output
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:

dart
void main() {
  String name = 'Ali';
  print(Name); // ✗ capital N
}
output
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.

dart
int studentAge = 20;
double productPrice = 250.0;
String studentName = 'Ali';

Compare:

dart
// 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

dart
void main() {
  int balance = 1000;
  print('Starting balance: $balance');
  balance = balance - 250;
  print('After purchase: $balance');
}
output
Starting balance: 1000
After purchase: 750

A 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

dart
void main() {
  String productName = 'Notebook';
  int price = 500;
  int quantity = 2;
  int total = price * quantity;
  print('Product: $productName');
  print('Total: $total');
}
output
Product: Notebook
Total: 1000

This is the important idea: store information in meaningful variables, process it, then use the result.


Code Examples

Example 1 — Basic Variables

dart
void main() {
  String name = 'Ali';
  int age = 20;
  print(name);
  print(age);
}
output
Ali
20

Example 2 — Different Types

dart
void main() {
  String name = 'Sara';
  int age = 18;
  double height = 5.6;
  bool isStudent = true;
  print(name);
  print(age);
  print(height);
  print(isStudent);
}
output
Sara
18
5.6
true

Example 3 — Interpolation

dart
void main() {
  String name = 'Zayan';
  int age = 6;
  print('Name: $name');
  print('Age: $age');
}
output
Name: Zayan
Age: 6

Example 4 — Updating a Value

dart
void main() {
  int score = 50;
  print(score);
  score = 75;
  print(score);
}
output
50
75

Example 5 — Calculation

dart
void main() {
  int price = 200;
  int quantity = 4;
  int total = price * quantity;
  print(total);
}
output
800

Example 6 — Multiple Updates

dart
void main() {
  int balance = 1000;
  balance = balance - 200;
  balance = balance + 50;
  print(balance);
}
output
850

How it works

  1. balance starts at 1000.
  2. balance - 200 is calculated as 800, and that result replaces the old value.
  3. balance + 50 is calculated as 850, and that result replaces the value again.
  4. Only the final value, 850, is printed.

Example 7 — Student Information

dart
void main() {
  String name = 'Zayan';
  int age = 6;
  String grade = '1';
  print('Name: $name');
  print('Age: $age');
  print('Grade: $grade');
}
output
Name: Zayan
Age: 6
Grade: 1

How it works

  1. Three variables hold three separate pieces of the same record.
  2. grade is a String, not an int, because a grade is a label rather than a number we calculate with.
  3. Each print builds a readable line using interpolation.

Example 8 — Shopping Total

dart
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');
}
output
Product: Notebook
Price: 500
Quantity: 3
Total: 1500

How it works

  1. price and quantity hold the inputs.
  2. total is a new variable holding a calculated result — 500 * 3, which is 1500.
  3. Because price and quantity are both int, their product is also an int.
  4. Changing quantity to 5 would update the total automatically; nothing else needs editing.

Example 9 — Temperature Conversion

dart
void main() {
  double celsius = 25;
  double fahrenheit = (celsius * 9 / 5) + 32;
  print('Celsius: $celsius');
  print('Fahrenheit: $fahrenheit');
}
output
Celsius: 25.0
Fahrenheit: 77.0

How it works

  1. celsius is declared double but written as 25 — allowed, and stored as 25.0 (see section 11).
  2. The brackets force the multiplication and division to happen before + 32.
  3. 25 * 9 / 5 is 45.0, and 45.0 + 32 is 77.0.
  4. Both values print with a decimal part because both are double.

Example 10 — Simple Score Update

dart
void main() {
  int score = 60;
  score = score + 15;
  score = score + 10;
  print('Final score: $score');
}
output
Final score: 85

How it works

  1. score starts at 60.
  2. score = score + 15 reads the old value, adds 15, and stores 75 back.
  3. The same pattern adds 10, giving 85.
  4. This "read, change, store back" pattern is how a running total works.

Common Beginner Mistakes

1. Reading a variable before it has a value

dart
void main() {
  String name;
  print(name);
}
output
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

dart
void main() {
  int age = 20;
  age = 'twenty';
}
output
Error: A value of type 'String' can't be assigned to a variable of type 'int'.

3. Getting the capital letters wrong

dart
void main() {
  String name = 'Ali';
  print(Name);
}
output
Error: Undefined name 'Name'.

name and Name are different variables. Dart will not guess.

4. Declaring a top-level variable without a value

dart
String name;
output
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:

output
Student: Ali
Total: 240

Try it yourself before opening the solution.

Show solution
dart
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');
}
output
Student: Ali
Total: 240

How it works

  1. Four variables hold the inputs: one name and three marks.
  2. total is calculated from the three marks: 80 + 75 + 85.
  3. The two print lines 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

  1. Create a String variable named city holding 'Lahore' and print it.
  2. Create int variables age = 20 and year = 2026, then print both, each on its own line.
  3. Create a double variable price = 99.5 and a bool variable inStock = true, then print both.

Application

  1. Store the name 'Sara' and age 18, then print them on one line using string interpolation, in the form Name: Sara, Age: 18.
  2. Store price = 250 and quantity = 4, calculate the total cost, and print only the total.
  3. Store score = 50, print it, change it to 80, then print it again.
  4. Store three subject marks — 80, 75, 85 — calculate their total, and print only the total.
  5. Store a rectangle's width = 12.5 and height = 4, calculate the area, and print it.

Challenge

  1. Store first = 'Ali' and second = 'Sara'. Swap their values so that first holds 'Sara' and second holds 'Ali', then print them as First: … and Second: …. Hint: you will need a third variable to hold one value temporarily.
  2. Write a receipt program. Store price = 1200, quantity = 3, and discountRate = 0.10. Calculate the subtotal, the discount amount, and the final total, then print all three labelled as Subtotal:, Discount:, and Total:.

Practice Answers

Question 1 — Solution

dart
void main() {
  String city = 'Lahore';
  print(city);
}
output
Lahore

Question 2 — Solution

dart
void main() {
  int age = 20;
  int year = 2026;
  print(age);
  print(year);
}
output
20
2026

Question 3 — Solution

dart
void main() {
  double price = 99.5;
  bool inStock = true;
  print(price);
  print(inStock);
}
output
99.5
true

Question 4 — Solution

dart
void main() {
  String name = 'Sara';
  int age = 18;
  print('Name: $name, Age: $age');
}
output
Name: Sara, Age: 18

Question 5 — Solution

dart
void main() {
  int price = 250;
  int quantity = 4;
  int total = price * quantity;
  print(total);
}
output
1000

Question 6 — Solution

dart
void main() {
  int score = 50;
  print(score);
  score = 80;
  print(score);
}
output
50
80

Question 7 — Solution

dart
void main() {
  int math = 80;
  int science = 75;
  int english = 85;
  int total = math + science + english;
  print(total);
}
output
240

Question 8 — Solution

dart
void main() {
  double width = 12.5;
  double height = 4;
  double area = width * height;
  print(area);
}
output
50.0

height is written as 4 but stored as 4.0, so the area prints as 50.0.

Question 9 — Solution

dart
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');
}
output
First: Sara
Second: Ali

Without temp, the first assignment would overwrite 'Ali' and it would be lost forever — second would end up holding 'Sara' as well.

Question 10 — Solution

dart
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');
}
output
Subtotal: 3600
Discount: 360.0
Total: 3240.0

subtotal 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

  1. What is a variable?
  2. What is the difference between declaring and initializing a variable?
  3. What does = do?
  4. Name four common Dart data types.
  5. How do you put a variable's value inside a string?
  6. What happens if you read a non-nullable local variable before assigning it?
  7. Why is Name not the same variable as name?
  8. Why does double price = 25; print 25.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, and bool.
  • A whole number written into a double is 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.


Video lecture

Subscribe
Placeholder video — the real recording isn't linked yet.