Watch the video (8 min)
On this page24 sections
  1. Prerequisites
  2. Connection With Previous Lectures
  3. Learning Objectives
  4. 1. What Is Type Inference?
  5. 2. Declaring a Variable with var
  6. 3. Which Type Does Dart Choose?
  7. 4. var Is Still Type-Safe
  8. 5. Changing a var Variable
  9. 6. The 25 vs 25.0 Trap
  10. 7. Inferring from a Calculation
  11. 8. var Without a Value
  12. 9. var and a Type Together
  13. 10. var at the Top Level
  14. 11. Choosing Between var and an Explicit Type
  15. 12. A Real-World Example
  16. Code Examples
  17. Common Beginner Mistakes
  18. Best Practices
  19. Mini Challenge
  20. Practice Questions
  21. Practice Answers
  22. Quick Revision
  23. Key Takeaways
  24. What's Next?

Lecture 05 — var & Type Inference

Category2 — Variables & Data Types
Lecture005 of 140
Estimated video length8 min
TargetDart 3.12.2
LevelBeginner

Writing String or int in front of every variable repeats what the value already says. With var, 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, and bool
  • why Dart rejects a value of the wrong type

Connection With Previous Lectures

In Lecture 004, every variable started with its type:

dart
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 var variable is still type-safe
  • Avoid the 25 versus 25.0 inference trap
  • Recognize why var without a value is risky
  • Choose between var and an explicit type
  • Recognize the error messages Dart produces for common var mistakes

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:

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

Dart 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 writeDart infers
var name = 'Sara';String
var age = 18;int
var price = 99.5;double
var isStudent = true;bool
dart
void main() {
  var name = 'Sara';
  var age = 18;
  var price = 99.5;
  var isStudent = true;
  print('$name, $age, $price, $isStudent');
}
output
Sara, 18, 99.5, true

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

dart
void main() {
  var 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';
        ^

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:

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

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

dart
void main() {
  var temperature = 25;
  temperature = 25.5;
  print(temperature);
}
output
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:

dart
void main() {
  var temperature = 25.0;
  temperature = 25.5;
  print(temperature);
}
output
25.5

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

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

int times int gives an int, so total is an int. Bring a double into the calculation and the result becomes a double:

dart
void main() {
  var price = 100;
  var discountRate = 0.5;
  var discount = price * discountRate;
  print(discount);
}
output
50.0

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

dart
void main() {
  var score;
  score = 10;
  print(score);
  score = 'ten';
  print(score);
}
output
10
ten

No 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 var variable its value on the same line.


9. var and a Type Together

var replaces the type. You write one or the other, never both:

dart
void main() {
  var int age = 20;
  print(age);
}
output
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:

dart
var appName = 'Dart Course';

void main() {
  print(appName);
}
output
Dart Course

11. Choosing Between var and an Explicit Type

Both styles create the same typed variable. The difference is what the reader sees.

  • Use var for 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 double that 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

dart
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');
}
output
Customer: Sara
Subtotal: 2400
Total: 2160.0

Not 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

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

Example 2 — Four Inferred Types

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

Example 3 — Interpolation with var

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

Example 4 — Updating a var Variable

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

Example 5 — Inferring from a Calculation

dart
void main() {
  var width = 8;
  var height = 5;
  var area = width * height;
  print(area);
}
output
40

Example 6 — A double from the Start

dart
void main() {
  var temperature = 30.0;
  print(temperature);
  temperature = 31.5;
  print(temperature);
}
output
30.0
31.5

How it works

  1. 30.0 has a decimal point, so Dart infers double.
  2. Because temperature is a double, assigning 31.5 is allowed.
  3. Had the first value been 30, the second assignment would have been an error.

Example 7 — Student Marks

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

How it works

  1. student is inferred as String; the three marks as int.
  2. total adds three int values, so it is an int too.
  3. The output is identical to the explicitly typed version from Lecture 004.

Example 8 — Shopping Total

dart
void main() {
  var product = 'Notebook';
  var price = 500;
  var quantity = 3;
  var total = price * quantity;
  print('Product: $product');
  print('Quantity: $quantity');
  print('Total: $total');
}
output
Product: Notebook
Quantity: 3
Total: 1500

How it works

  1. price and quantity are inferred as int.
  2. total is inferred from price * quantity, an int result: 1500.
  3. Changing quantity updates the total; no type needs editing.

Example 9 — Bank Balance

dart
void main() {
  var balance = 1000.0;
  var deposit = 250.5;
  var withdrawal = 100;
  balance = balance + deposit;
  balance = balance - withdrawal;
  print('Balance: $balance');
}
output
Balance: 1150.5

How it works

  1. balance starts as 1000.0, so it is a double — ready for amounts with cents.
  2. deposit is a double; withdrawal is an int.
  3. balance + deposit and balance - withdrawal both produce a double, which balance can hold.
  4. Starting with 1000 instead of 1000.0 would make balance an int, and the first update would be rejected.

Example 10 — Temperature Conversion

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

How it works

  1. celsius is a double because of 25.0.
  2. fahrenheit is inferred from the calculation. Division with / always gives a double, so fahrenheit is a double.
  3. 25.0 * 9 / 5 is 45.0, and 45.0 + 32 is 77.0.

Common Beginner Mistakes

1. Expecting var to accept any type

dart
void main() {
  var age = 20;
  // age = 'twenty'; // ✗
}
output
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

dart
void main() {
  var temperature = 25;
  // temperature = 25.5; // ✗
}
output
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

dart
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

dart
void main() {
  // var int age = 20; // ✗
}
output
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

dart
void main() {
  var name = 'Ali';
  // var name = 'Sara'; // ✗
}
output
Error: 'name' is already declared in this scope.

To change it, drop the var: name = 'Sara';.


Best Practices

  • Use var for local variables when the value makes the type obvious.
  • Always initialize a var variable 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 var and 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:

output
Owner: Zayan
Balance: 170

Try it yourself before opening the solution.

Show solution
dart
void main() {
  var owner = 'Zayan';
  var balance = 150;
  balance = balance + 50;
  balance = balance - 30;
  print('Owner: $owner');
  print('Balance: $balance');
}
output
Owner: Zayan
Balance: 170

How it works

  1. owner is inferred as String and balance as int.
  2. Every amount is a whole number, so balance stays an int throughout.
  3. 150 + 50 - 30 gives 170.

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. Use var to store the city 'Karachi' and print it.
  2. Use var to store age = 21 and height = 5.9, then print both, each on its own line.
  3. 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

  1. Store price = 450 and quantity = 2 with var, calculate the total with var, and print Total: 900.

  2. Store score = 40 with var, add 25 to it, and print the new score.

  3. Store a rectangle's width = 12.5 and height = 4 with var, calculate the area, and print it.

  4. This program does not compile. Fix it by changing one character, so that it prints 36.6:

    dart
    void main() {
      var temperature = 36;
      temperature = 36.6;
      print(temperature);
    }
  5. Rewrite this program using var everywhere a type is written, without changing the output:

    dart
    void main() {
      String name = 'Sara';
      int math = 90;
      int science = 85;
      int total = math + science;
      print('$name: $total');
    }

Challenge

  1. Sara's account starts at 2000.0. She deposits 500 and is then charged a fee of 12.5. Use only var, and print Balance: 2487.5.
  2. A shop sells a bag for 1500. There is a 20% discount. Using only var, calculate the discount and the final price, then print Discount: 300.0 and Final price: 1200.0. Explain in one sentence why both values print with .0.

Practice Answers

Question 1 — Solution

dart
void main() {
  var city = 'Karachi';
  print(city);
}
output
Karachi

Question 2 — Solution

dart
void main() {
  var age = 21;
  var height = 5.9;
  print(age);
  print(height);
}
output
21
5.9

Question 3 — Solution

a is a String, b an int, c a double, and d a bool.

dart
void main() {
  var a = 'Hi';
  var b = 7;
  var c = 7.0;
  var d = false;
  print('$a, $b, $c, $d');
}
output
Hi, 7, 7.0, false

7.0 keeps its decimal part when printed because c is a double.

Question 4 — Solution

dart
void main() {
  var price = 450;
  var quantity = 2;
  var total = price * quantity;
  print('Total: $total');
}
output
Total: 900

Question 5 — Solution

dart
void main() {
  var score = 40;
  score = score + 25;
  print(score);
}
output
65

Question 6 — Solution

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

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

dart
void main() {
  var temperature = 36.0;
  temperature = 36.6;
  print(temperature);
}
output
36.6

Question 8 — Solution

dart
void main() {
  var name = 'Sara';
  var math = 90;
  var science = 85;
  var total = math + science;
  print('$name: $total');
}
output
Sara: 175

Question 9 — Solution

dart
void main() {
  var balance = 2000.0;
  balance = balance + 500;
  balance = balance - 12.5;
  print('Balance: $balance');
}
output
Balance: 2487.5

Starting 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

dart
void main() {
  var price = 1500;
  var discountRate = 0.2;
  var discount = price * discountRate;
  var finalPrice = price - discount;
  print('Discount: $discount');
  print('Final price: $finalPrice');
}
output
Discount: 300.0
Final price: 1200.0

Both print with .0 because discountRate is a double, so discount is inferred as a double — and price - discount is a double too.


Quick Revision

  1. What does type inference mean?
  2. What does Dart look at to decide a var variable's type?
  3. Can a var variable hold a String and later an int?
  4. Which type does var temperature = 25; produce? And var temperature = 25.0;?
  5. What happens to type checking when you write var score; with no value?
  6. Why is var int age = 20; an error?
  7. When is an explicit type clearer than var?

Key Takeaways

  • Type inference means Dart decides a variable's type from its value.
  • var replaces the type name; the variable is still fully typed.
  • The type is fixed by the first value and checked on every later assignment.
  • 25 infers int and 25.0 infers double — choose the first value carefully.
  • A calculation's result type becomes the variable's type.
  • var without a value switches type checking off — always initialize it.
  • Write var or a type, never both.
  • Use var for 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.


Video lecture

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