Variables and Constants in Dart
By Syncfusion®, Inc. · Last updated
How to store values in variables, the rules for naming them, and when to use var, final and const.
What Is a Variable?
Variable = a named box in the computer's memory that holds a value.
For example:
namecan hold'Asha'agecan hold13markscan hold92
You give the box a name once. Then you use the name, and Dart finds the value inside.
Simple lesson: a variable is a box with a name, so your program can remember things.
A Real-World Example
Every student has a roll-number card in the school office.
- The label on the card is the student's name.
- The value written on it is the roll number.
- When the student changes class, the office writes a new value on the same card.
A variable works the same way: one label, one value, and the value can change.
Every Run box on this page uses the course's Dart runner, right here in your browser.
Some boxes fail on purpose, to show you a real Dart error.
What You Will Learn
In this lesson, you will learn:
- What variables are and why we use them.
- How to declare, assign, change and print a variable.
- The rules for naming variables, and Dart's keywords.
- How
var,finalandconstare different. - When to use each one.
Why We Use Variables
Without variables, you would type the same value again and again.
Variables help you:
- remember a value, like a student's name
- change a value, like marks after a re-test
- reuse a value, in many places, by its name
- read the code easily, because
totalMarksexplains itself and437does not
Simple lesson: variables save typing, and they make code easy to read and change.
Creating Variables
Declaration
Declaration = telling Dart "make a new box with this name".
var studentName;
Initialization
Initialization = putting the first value into the box, while you create it.
var studentName = 'Asha';
var= make a new variable.studentName= the name of the box.== put the value on the right into the box on the left.'Asha'= the value.
Your First Variables
Press Run.
Three variables about one student
void main() {
var name = 'Asha';
var age = 13;
var className = '8B';
print(name);
print(age);
print(className);
}
print(name) prints the value inside the box, not the word "name".
Simple lesson: declare a variable and give it a first value in one line: var name = 'Asha';.
Changing a Variable
Assignment and Reassignment
Assignment = putting a value into a variable with =.
Reassignment = putting a new value into a variable that already has one.
- You write
varonly once, when you create the variable. - After that, use just the name:
age = 14; - The old value is gone. The box holds only the new one.
Press Next step to watch the box change.
Watch the memory boxes change
Look at line 6: age = age + 1;
- Dart works out the right side first:
14 + 1is15. - Then it puts the answer into the left side.
Printing Variables Inside Text
Put $ before a variable name inside text, and Dart puts its value there.
Printing variables inside a sentence
void main() {
var name = 'Ravi';
var marks = 88;
print('$name scored $marks marks.');
marks = 94;
print('After the re-test, $name scored $marks marks.');
}
This is called string interpolation. You will learn it properly in Strings.
Simple lesson: use var once to create, then just the name to change the value.
Naming Variables
What Are Identifiers?
Identifier = a name you choose, for a variable, a function or anything else.
The Naming Rules
Dart allows a name only if it follows these rules:
- It uses letters, digits,
_and$only. - It does not start with a digit.
- It has no spaces.
- It is not a keyword, like
varorif. - It is case-sensitive:
marksandMarksare two different names.
Valid or Invalid?
Sort each name into the right box.
Click a name, then click Valid or Invalid
Naming Conventions
Convention = a habit that every Dart programmer follows, so code looks the same everywhere.
| What | Style | Example |
|---|---|---|
| Variables and functions | lowerCamelCase | totalMarks, studentName |
| Classes and types | UpperCamelCase | Student, ReportCard |
| File names | lowercase_with_underscores | report_card.dart |
lowerCamelCase = the first word in small letters, every next word starts with a capital.
Good names explain the value:
- Good:
totalMarks,isAbsent,schoolName - Poor:
x,t,data2
Dart Keywords
Keyword = a word that already has a special meaning in Dart.
You cannot use a keyword as a name. Here are some you will meet soon:
var,final,const,lateif,else,switch,casefor,while,do,break,continuevoid,return,true,false,nullclass,import,is,as
Using one as a name fails:
var class = '8B';
Dart says: Expected an identifier, but got 'class'. Use a name like className instead.
Dart is case-sensitive.
marks, Marks and MARKS are three different names. A wrong capital letter gives Undefined name.
Simple lesson: start names with a letter, use lowerCamelCase, and never use a keyword.
var, final and const
Dart has three ways to create a variable. They differ in whether the value can change, and when the value is known.
Click each one to compare
var
var = make a variable whose value can change.
- Dart works out the type from the first value.
var age = 13;makes anint. - You can give it a new value of the same type later.
final
final = a variable that gets its value only once.
- Single assignment rule: after the first value, it can never change.
- The value can be decided while the program runs, for example from input.
Runtime constant = a value that is fixed, but only known once the program runs.
Type your name in the Input box, then press Run.
A final value that comes from the user
import 'dart:io';
void main() {
print('Enter your name:');
final name = stdin.readLineSync();
print('Welcome, $name! Your name is now fixed.');
}
Now try to change a final variable:
A final variable cannot change
void main() {
final rollNumber = 21;
rollNumber = 22;
print(rollNumber);
}
Dart says: Can't assign to the final variable 'rollNumber'. The program does not even start.
const
const = a value that is fixed before the program runs.
Compile-time constant = a value Dart knows while it reads your code, before running anything.
Constant expression = a calculation made only of constant values, like 60 * 60.
Fixed facts with const
void main() {
const daysInWeek = 7;
const secondsInHour = 60 * 60;
const pi = 3.14;
print('A week has $daysInWeek days.');
print('An hour has $secondsInHour seconds.');
print('A circle of radius 2.5 has area ${pi * 2.5 * 2.5}.');
}
60 * 60 is allowed, because both numbers are constants.
A value from the user is not known before the program runs:
const needs a value known before the program runs
import 'dart:io';
void main() {
const name = stdin.readLineSync();
print(name);
}
Dart says: Method invocation is not a constant expression. Use final here instead.
Simple lesson: var can change, final is set once while running, and const is fixed before running.
final vs const
How They Are the Same
- Neither can be changed after it gets a value.
- Both make your code safer, because nobody can change the value by mistake.
How They Are Different
| Question | final | const |
|---|---|---|
| Can the value change? | No | No |
| When is the value known? | When the program runs | Before the program runs |
| Can it come from user input? | Yes | No |
| Example | final name = stdin.readLineSync(); | const pi = 3.14; |
When to Use Each
Ask two questions:
- Will this value ever change? If yes, use
var. - Do I know the value while writing the code? If yes, use
const. If no, usefinal.
Easy way to remember
var= a whiteboard. Write, wipe, write again.final= a pen on paper. You choose what to write on the day, but you cannot erase it.const= printed in the textbook. It was fixed before you even opened the book.
Good Dart programmers use final often.
If a value never changes, final tells every reader so.
Simple lesson: prefer final, use const for fixed facts, and use var only when the value really changes.
TL;DR
Variable = a named box that holds a value.
- Create:
var age = 13; - Change:
age = 14;
- Create:
Identifier = a name you choose.
- Letters, digits,
_,$. No digit first. No spaces. No keywords. - Use lowerCamelCase:
totalMarks.
- Letters, digits,
var= the value can change.final= set once, value known when the program runs.const= set once, value known before the program runs.
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
var age = 13; then var age = 14; | var is needed every time | Use var only once, then age = 14; | The name is declared twice, an error. |
Changing a final variable | final is like var | A final value is set only once | Can't assign to the final variable. |
const with user input | const and final are the same | Input is only known at run time, so use final | Method invocation is not a constant expression. |
| A name starting with a digit | 2ndRank is fine | Start with a letter: secondRank | A syntax error. |
| A keyword as a name | var class = '8B'; works | Choose another name: className | Expected an identifier. |
| Wrong case | Marks and marks are the same | Dart is case-sensitive | Undefined name 'Marks'. |
| A new type of value | var age = 13; then age = 'thirteen'; | A var keeps the type of its first value | A value of type 'String' can't be assigned. |
Check Yourself
Exercises
What to Remember
- A variable is a named box. Create it with
varonce, then change it by name. - Names use letters, digits,
_and$, never start with a digit, and are never keywords. - Write variable names in lowerCamelCase, like
totalMarks. finalis set once while the program runs.constis fixed before it runs.- Prefer
final, and usevaronly when the value really changes.
Next: Data Types. You will learn the kinds of values a variable can hold, like whole numbers, decimals, text and true or false.