On this page24 sections
- Prerequisites
- Connection With Previous Lectures
- Learning Objectives
- 1. What Is Type Inference?
- 2. Declaring a Variable with var
- 3. Which Type Does Dart Choose?
- 4. var Is Still Type-Safe
- 5. Changing a var Variable
- 6. The 25 vs 25.0 Trap
- 7. Inferring from a Calculation
- 8. var Without a Value
- 9. var and a Type Together
- 10. var at the Top Level
- 11. Choosing Between var and an Explicit Type
- 12. 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 05 — var & Type Inference
| Category | 2 — Variables & Data Types |
| Lecture | 005 of 140 |
| Estimated video length | 8 min |
| Target | Dart 3.12.2 |
| Level | Beginner |
Writing
Stringorintin front of every variable repeats what the value already says. Withvar, Dart reads the type from the value — and still checks every assignment.
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–004:
main(),print(), and string interpolation with$- declaring, initializing, and assigning variables
- the types
String,int,double, andbool - why Dart rejects a value of the wrong type
Connection With Previous Lectures
In Lecture 004, every variable started with its type:
String name = 'Ali';
int age = 20;
double price = 99.5;
bool isStudent = true;Look at each line. 'Ali' is obviously text, 20 is obviously a whole number. The type in
front says the same thing a second time. In a long program, that repetition adds up — and if
you change a value, you may have to change its type too. Dart can work the type out for you.
Learning Objectives
By the end of this lecture you will be able to:
- Explain what type inference means
- Declare variables with
var - Predict which type Dart infers from a value
- Prove that a
varvariable is still type-safe - Avoid the
25versus25.0inference trap - Recognize why
varwithout a value is risky - Choose between
varand an explicit type - Recognize the error messages Dart produces for common
varmistakes
1. What Is Type Inference?
Type inference means Dart looks at the value you give a variable and decides the type itself.
Analogy — think of a shop assistant packing boxes. You hand over a pair of shoes; the assistant sees what they are and writes "Shoes" on the label for you. From then on, that box is a shoe box.
You still get a typed variable. You just don't have to write the type.
2. Declaring a Variable with var
Replace the type with the keyword var:
void main() {
var name = 'Ali';
var age = 20;
print(name);
print(age);
}Ali
20Dart sees 'Ali' and makes name a String. It sees 20 and makes age an int. The
program behaves exactly as if you had written the types yourself.
3. Which Type Does Dart Choose?
Dart chooses the type from the first value:
| You write | Dart infers |
|---|---|
var name = 'Sara'; | String |
var age = 18; | int |
var price = 99.5; | double |
var isStudent = true; | bool |
void main() {
var name = 'Sara';
var age = 18;
var price = 99.5;
var isStudent = true;
print('$name, $age, $price, $isStudent');
}Sara, 18, 99.5, trueDart can also tell you a variable's type while the program runs — we will see how in Lecture 010.
4. var Is Still Type-Safe
Once Dart has chosen a type, that type is fixed. A var variable is not a box that holds
anything — it is a normal typed variable:
void main() {
var age = 20;
age = 'twenty';
print(age);
}Error: A value of type 'String' can't be assigned to a variable of type 'int'.
age = 'twenty';
^Read the message carefully: a variable of type int. We never wrote int — Dart inferred
it from 20, and now it protects that choice exactly as in Lecture 004.
5. Changing a var Variable
A var variable can still change, as long as the new value has the same type:
void main() {
var score = 10;
print(score);
score = 20;
print(score);
}10
20var means "work out the type for me", not "this value never changes". Variables that
never change are the topic of the next lecture, final and const.
6. The 25 vs 25.0 Trap
Here is the most common surprise with var. Dart infers from the value exactly as you
wrote it:
void main() {
var temperature = 25;
temperature = 25.5;
print(temperature);
}Error: A value of type 'double' can't be assigned to a variable of type 'int'.
temperature = 25.5;
^25 has no decimal point, so temperature became an int — and an int cannot hold
25.5. If a value may ever have a decimal part, start it with one:
void main() {
var temperature = 25.0;
temperature = 25.5;
print(temperature);
}25.5Writing double temperature = 25; would also work. When you want a double but your first
value is a whole number, the explicit type says so clearly.
7. Inferring from a Calculation
The value does not have to be typed out — it can be the result of a calculation. Dart infers the type of the result:
void main() {
var price = 100;
var quantity = 3;
var total = price * quantity;
print(total);
}300int times int gives an int, so total is an int. Bring a double into the
calculation and the result becomes a double:
void main() {
var price = 100;
var discountRate = 0.5;
var discount = price * discountRate;
print(discount);
}50.08. var Without a Value
var needs a value to infer from. Without one, Dart has nothing to read — so it stops
checking the type at all:
void main() {
var score;
score = 10;
print(score);
score = 'ten';
print(score);
}10
tenNo error. score held a number, then text, and Dart allowed both. That is the type safety
from section 4 switched off. This kind of variable is called dynamic. We will study
dynamic properly in Lecture 011.
Rule: always give a
varvariable its value on the same line.
9. var and a Type Together
var replaces the type. You write one or the other, never both:
void main() {
var int age = 20;
print(age);
}Error: Variables can't be declared using both 'var' and a type name.
Try removing 'var.'
var int age = 20;
^^^Either var age = 20; or int age = 20; — both are correct.
10. var at the Top Level
var also works outside main(), at the top of the file. As with any top-level variable,
give it its value right there:
var appName = 'Dart Course';
void main() {
print(appName);
}Dart Course11. Choosing Between var and an Explicit Type
Both styles create the same typed variable. The difference is what the reader sees.
- Use
varfor variables inside a function when the value makes the type obvious:var name = 'Ali';,var total = price * quantity;. - Use an explicit type when the value does not say what you mean — especially a
doublethat starts as a whole number:double balance = 1000;.
Dart's official style guide recommends var for local variables, so most of this course
uses it from now on.
12. A Real-World Example
void main() {
var customer = 'Sara';
var price = 1200;
var quantity = 2;
var discountRate = 0.1;
var subtotal = price * quantity;
var discount = subtotal * discountRate;
var total = subtotal - discount;
print('Customer: $customer');
print('Subtotal: $subtotal');
print('Total: $total');
}Customer: Sara
Subtotal: 2400
Total: 2160.0Not one type is written, yet every variable has one: customer is a String, subtotal an
int, and discount and total are double because discountRate is a double.
Code Examples
Example 1 — Basic var
void main() {
var name = 'Ali';
var age = 20;
print(name);
print(age);
}Ali
20Example 2 — Four Inferred Types
void main() {
var name = 'Sara';
var age = 18;
var height = 5.6;
var isStudent = true;
print(name);
print(age);
print(height);
print(isStudent);
}Sara
18
5.6
trueExample 3 — Interpolation with var
void main() {
var name = 'Zayan';
var age = 6;
print('Name: $name');
print('Age: $age');
}Name: Zayan
Age: 6Example 4 — Updating a var Variable
void main() {
var score = 50;
print(score);
score = 75;
print(score);
}50
75Example 5 — Inferring from a Calculation
void main() {
var width = 8;
var height = 5;
var area = width * height;
print(area);
}40Example 6 — A double from the Start
void main() {
var temperature = 30.0;
print(temperature);
temperature = 31.5;
print(temperature);
}30.0
31.5How it works
30.0has a decimal point, so Dart infersdouble.- Because
temperatureis adouble, assigning31.5is allowed. - Had the first value been
30, the second assignment would have been an error.
Example 7 — Student Marks
void main() {
var student = 'Ali';
var math = 80;
var science = 75;
var english = 85;
var total = math + science + english;
print('Student: $student');
print('Total: $total');
}Student: Ali
Total: 240How it works
studentis inferred asString; the three marks asint.totaladds threeintvalues, so it is aninttoo.- The output is identical to the explicitly typed version from Lecture 004.
Example 8 — Shopping Total
void main() {
var product = 'Notebook';
var price = 500;
var quantity = 3;
var total = price * quantity;
print('Product: $product');
print('Quantity: $quantity');
print('Total: $total');
}Product: Notebook
Quantity: 3
Total: 1500How it works
priceandquantityare inferred asint.totalis inferred fromprice * quantity, anintresult:1500.- Changing
quantityupdates the total; no type needs editing.
Example 9 — Bank Balance
void main() {
var balance = 1000.0;
var deposit = 250.5;
var withdrawal = 100;
balance = balance + deposit;
balance = balance - withdrawal;
print('Balance: $balance');
}Balance: 1150.5How it works
balancestarts as1000.0, so it is adouble— ready for amounts with cents.depositis adouble;withdrawalis anint.balance + depositandbalance - withdrawalboth produce adouble, whichbalancecan hold.- Starting with
1000instead of1000.0would makebalanceanint, and the first update would be rejected.
Example 10 — Temperature Conversion
void main() {
var celsius = 25.0;
var fahrenheit = celsius * 9 / 5 + 32;
print('Celsius: $celsius');
print('Fahrenheit: $fahrenheit');
}Celsius: 25.0
Fahrenheit: 77.0How it works
celsiusis adoublebecause of25.0.fahrenheitis inferred from the calculation. Division with/always gives adouble, sofahrenheitis adouble.25.0 * 9 / 5is45.0, and45.0 + 32is77.0.
Common Beginner Mistakes
1. Expecting var to accept any type
void main() {
var age = 20;
// age = 'twenty'; // ✗
}Error: A value of type 'String' can't be assigned to a variable of type 'int'.var picks a type once. After that, the variable is as strict as int age = 20;.
2. Starting a decimal value as a whole number
void main() {
var temperature = 25;
// temperature = 25.5; // ✗
}Error: A value of type 'double' can't be assigned to a variable of type 'int'.Write var temperature = 25.0; or double temperature = 25;.
3. Declaring var without a value
void main() {
var score; // ✗ no value to infer from
score = 10;
score = 'ten'; // no error — type checking is gone
}No error appears, which is exactly the problem. Give the value on the same line.
4. Writing var and a type together
void main() {
// var int age = 20; // ✗
}Error: Variables can't be declared using both 'var' and a type name.Keep one: var age = 20; or int age = 20;.
5. Thinking var means "cannot change"
var only decides the type. A var variable can be reassigned freely. Values that must not
change use final or const (Lecture 006).
6. Declaring the same name twice
void main() {
var name = 'Ali';
// var name = 'Sara'; // ✗
}Error: 'name' is already declared in this scope.To change it, drop the var: name = 'Sara';.
Best Practices
- Use
varfor local variables when the value makes the type obvious. - Always initialize a
varvariable on the same line. - Write a decimal point (
25.0) when a number may later need a decimal part. - Use an explicit type when it states your intent better than the value does.
- Keep descriptive lowerCamelCase names — with no type on the line, the name carries the meaning.
- Never write
varand a type together.
Mini Challenge
Write a program for Zayan's piggy bank using only var. He starts with 150 rupees, receives
50 from his uncle, then spends 30 on a book. Print the final balance.
Your program should print exactly:
Owner: Zayan
Balance: 170Try it yourself before opening the solution.
Show solution
void main() {
var owner = 'Zayan';
var balance = 150;
balance = balance + 50;
balance = balance - 30;
print('Owner: $owner');
print('Balance: $balance');
}Owner: Zayan
Balance: 170How it works
owneris inferred asStringandbalanceasint.- Every amount is a whole number, so
balancestays anintthroughout. 150 + 50 - 30gives170.
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
- Use
varto store the city'Karachi'and print it. - Use
varto storeage = 21andheight = 5.9, then print both, each on its own line. - Which type does Dart infer for each of these:
var a = 'Hi';,var b = 7;,var c = 7.0;,var d = false;? Write a program that prints all four values on one line, separated by commas.
Application
-
Store
price = 450andquantity = 2withvar, calculate the total withvar, and printTotal: 900. -
Store
score = 40withvar, add25to it, and print the new score. -
Store a rectangle's
width = 12.5andheight = 4withvar, calculate the area, and print it. -
This program does not compile. Fix it by changing one character, so that it prints
36.6:void main() { var temperature = 36; temperature = 36.6; print(temperature); } -
Rewrite this program using
vareverywhere a type is written, without changing the output:void main() { String name = 'Sara'; int math = 90; int science = 85; int total = math + science; print('$name: $total'); }
Challenge
- Sara's account starts at
2000.0. She deposits500and is then charged a fee of12.5. Use onlyvar, and printBalance: 2487.5. - A shop sells a bag for
1500. There is a20%discount. Using onlyvar, calculate the discount and the final price, then printDiscount: 300.0andFinal price: 1200.0. Explain in one sentence why both values print with.0.
Practice Answers
Question 1 — Solution
void main() {
var city = 'Karachi';
print(city);
}KarachiQuestion 2 — Solution
void main() {
var age = 21;
var height = 5.9;
print(age);
print(height);
}21
5.9Question 3 — Solution
a is a String, b an int, c a double, and d a bool.
void main() {
var a = 'Hi';
var b = 7;
var c = 7.0;
var d = false;
print('$a, $b, $c, $d');
}Hi, 7, 7.0, false7.0 keeps its decimal part when printed because c is a double.
Question 4 — Solution
void main() {
var price = 450;
var quantity = 2;
var total = price * quantity;
print('Total: $total');
}Total: 900Question 5 — Solution
void main() {
var score = 40;
score = score + 25;
print(score);
}65Question 6 — Solution
void main() {
var width = 12.5;
var height = 4;
var area = width * height;
print(area);
}50.0height is an int, but width is a double, so the result — and area — is a double.
Question 7 — Solution
Add .0 to the first value, so Dart infers double instead of int:
void main() {
var temperature = 36.0;
temperature = 36.6;
print(temperature);
}36.6Question 8 — Solution
void main() {
var name = 'Sara';
var math = 90;
var science = 85;
var total = math + science;
print('$name: $total');
}Sara: 175Question 9 — Solution
void main() {
var balance = 2000.0;
balance = balance + 500;
balance = balance - 12.5;
print('Balance: $balance');
}Balance: 2487.5Starting with 2000.0 makes balance a double, so it can hold 2487.5. Starting with
2000 would make the fee line an error.
Question 10 — Solution
void main() {
var price = 1500;
var discountRate = 0.2;
var discount = price * discountRate;
var finalPrice = price - discount;
print('Discount: $discount');
print('Final price: $finalPrice');
}Discount: 300.0
Final price: 1200.0Both print with .0 because discountRate is a double, so discount is inferred as a
double — and price - discount is a double too.
Quick Revision
- What does type inference mean?
- What does Dart look at to decide a
varvariable's type? - Can a
varvariable hold aStringand later anint? - Which type does
var temperature = 25;produce? Andvar temperature = 25.0;? - What happens to type checking when you write
var score;with no value? - Why is
var int age = 20;an error? - When is an explicit type clearer than
var?
Key Takeaways
- Type inference means Dart decides a variable's type from its value.
varreplaces the type name; the variable is still fully typed.- The type is fixed by the first value and checked on every later assignment.
25infersintand25.0infersdouble— choose the first value carefully.- A calculation's result type becomes the variable's type.
varwithout a value switches type checking off — always initialize it.- Write
varor a type, never both. - Use
varfor obvious local values, and an explicit type when it states your intent better.
What's Next?
Lecture 06 — final, const & late. var decides a variable's type, but the value can
still change at any time. Many values — a tax rate, a student's ID, the number of days in a
week — should never change once set. Next we will learn how final and const lock a value
in place, and how late lets you set a value later safely.