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:

  • name can hold 'Asha'
  • age can hold 13
  • marks can hold 92

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:

  1. What variables are and why we use them.
  2. How to declare, assign, change and print a variable.
  3. The rules for naming variables, and Dart's keywords.
  4. How var, final and const are different.
  5. 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 totalMarks explains itself and 437 does 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 var only 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 + 1 is 15.
  • 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 var or if.
  • It is case-sensitive: marks and Marks are 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.

WhatStyleExample
Variables and functionslowerCamelCasetotalMarks, studentName
Classes and typesUpperCamelCaseStudent, ReportCard
File nameslowercase_with_underscoresreport_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, late
  • if, else, switch, case
  • for, while, do, break, continue
  • void, return, true, false, null
  • class, 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 an int.
  • 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

Questionfinalconst
Can the value change?NoNo
When is the value known?When the program runsBefore the program runs
Can it come from user input?YesNo
Examplefinal name = stdin.readLineSync();const pi = 3.14;

When to Use Each

Ask two questions:

  1. Will this value ever change? If yes, use var.
  2. Do I know the value while writing the code? If yes, use const. If no, use final.

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

  1. Variable = a named box that holds a value.

    • Create: var age = 13;
    • Change: age = 14;
  2. Identifier = a name you choose.

    • Letters, digits, _, $. No digit first. No spaces. No keywords.
    • Use lowerCamelCase: totalMarks.
  3. var = the value can change.
  4. final = set once, value known when the program runs.
  5. const = set once, value known before the program runs.

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
var age = 13; then var age = 14;var is needed every timeUse var only once, then age = 14;The name is declared twice, an error.
Changing a final variablefinal is like varA final value is set only onceCan't assign to the final variable.
const with user inputconst and final are the sameInput is only known at run time, so use finalMethod invocation is not a constant expression.
A name starting with a digit2ndRank is fineStart with a letter: secondRankA syntax error.
A keyword as a namevar class = '8B'; worksChoose another name: classNameExpected an identifier.
Wrong caseMarks and marks are the sameDart is case-sensitiveUndefined name 'Marks'.
A new type of valuevar age = 13; then age = 'thirteen';A var keeps the type of its first valueA value of type 'String' can't be assigned.

Check Yourself

Exercises

What to Remember

  • A variable is a named box. Create it with var once, 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.
  • final is set once while the program runs. const is fixed before it runs.
  • Prefer final, and use var only 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.