On this page13 sections
Lecture 006 — Declaring & Initializing Variables
| Category | 3 — Variables & Constants |
| Lecture | 006 of 057 |
| Estimated video length | 12 min |
| Target | Dart 3.12 |
| Level | Beginner |
A variable is a named box that holds a value. We create boxes (declare), put a first value in (initialize), change the value, and learn the naming rules and keywords.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 004–005: main, print and comments.
Learning Objectives
- Tell declaring a variable from initializing it
- Declare with a type or with
var - Change a variable's value
- Put variables inside strings with
$ - Follow Dart's naming rules and avoid keywords
1. Declare and Initialize
String city = 'Lahore';Read it as: type String, name city, =, value 'Lahore'.
- Declaring creates the box:
String city. - Initializing puts the first value in:
= 'Lahore'.
You can do both at once (above) or in two steps:
int age; // declared
age = 21; // initialized
print(age); // 21Dart won't let you read a variable before it has a value — that is caught before the program runs.
2. var — Let Dart Work Out the Type
var city = 'Lahore'; // Dart sees a String
var students = 30; // Dart sees an intThe type is still fixed — var only saves you typing it:
var students = 30;
students = 31; // fine: still an int
// students = 'many'; // error: a String can't go in an int variable3. Changing a Value
int score = 10;
score = 15;
score = score + 5; // now 20Write the type only the first time. After that, just the name.
4. Variables in Text
var name = 'Bilal';
var age = 19;
print('$name is $age years old.');
print('Next year: ${age + 1}');$name puts a variable in a string; ${...} puts a whole expression in. Lecture 009 covers
this in depth.
5. Naming Rules
- Letters, digits,
_and$only; can't start with a digit —2nd✗,second✓. - No spaces —
total price✗,totalPrice✓. - Case matters —
ageandAgeare different variables. - Style: lowerCamelCase —
totalPrice,isLoggedIn.
6. Keywords
Keywords are words Dart has reserved for itself, so they can't be variable names:
| Some keywords |
|---|
var final const void if else for while do switch case break continue return class new this true false null import try catch throw |
// var class = 'A'; // error: class is a keyword
var className = 'A'; // fineCode Examples
Example 1 — A Student Card
void main() {
String name = 'Zainab';
int rollNumber;
rollNumber = 42; // initialized later
var course = 'Dart Basic';
var day = 3;
print('Name: $name');
print('Roll number: $rollNumber');
print('$course — Day $day');
day = day + 1; // a new day
print('Tomorrow is Day $day');
}Output
Name: Zainab
Roll number: 42
Dart Basic — Day 3
Tomorrow is Day 4Common Beginner Mistakes
1. Using a variable before giving it a value — int x; print(x); gives "The non-nullable
local variable 'x' must be assigned before it can be used."
2. Re-declaring — writing int score = 15; a second time is an error. Write score = 15;.
3. Expecting var to accept any type later — it locks in the first type it sees.
4. Using a keyword as a name — var if = 1; doesn't compile.
Practice Questions
- What is the difference between declaring and initializing?
- What type does
var total = 9.99;have? - Which of these names are valid:
myAge,2cars,first_name,class? - Print "Ali has 3 books" using two variables.
Practice Answers
- Declaring creates the variable; initializing gives it its first value.
double.myAgeandfirst_name(thoughfirstNameis Dart style).2carsstarts with a digit;classis a keyword.var name = 'Ali'; var books = 3; print('$name has $books books');
Key Takeaways
- Declare = create the box; initialize = give it its first value.
varinfers the type once; it can't change type later.$nameand${expression}put values into strings.- Names: lowerCamelCase, no leading digit, no keywords.