Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 2

Declaring Dart Variables with Types, `var`, and `final`

This lesson is built with resources from youtube.com and dart.dev.

Hello! Last time, you ran a Dart file and used print to display fixed text. Now you’ll give values names, so a program can store and update information before printing it. In this lesson, you’ll declare variables with explicit types, let Dart infer a type with var, and use final when a variable should be assigned only once. Plan on about 35–40 minutes, including a short video and time to run the examples.


A name for a value

A variable is a name you can use to access a value. Put this inside main():

String category = 'Food';
print(category);

String is the type: it tells Dart that category holds text. The = assigns its initial value, and print(category) displays Food. Notice that there are no quotes around category in the print call. Quotes would print the literal word category instead.

Dart has other basic types you can name explicitly:

String category = 'Food';   // Text
int itemCount = 2;          // Whole number
double estimatedCost = 12.5; // Number with a decimal part
bool isPlanned = true;      // true or false

The type constrains later assignments. You may change category to another String, but not to a number:

category = 'Transport'; // Allowed
// category = 42;       // Not allowed: 42 is not a String

The video below shows both the declaration itself and what happens when an assignment has the wrong type.

Introduction to Dart - Part 1: Variables and Types

Watch Introduction to Dart - Part 1: Variables and Types by Andrea Bizzotto for a visual explanation of variable declarations, type inference, and reassignment.

Begin with a variable declaration, paying attention to the type, name, and initial value. Then watch types and var to see explicit types compared with inferred ones. Finish with reassignment and final; focus on why changing a value is allowed in one declaration but rejected in another.



var leaves the type for Dart to infer

When you provide an initial value, you can write var instead of spelling out the type:

var category = 'Food';
var itemCount = 2;

Dart infers String for category and int for itemCount. var does not mean “any type.” These variables still have types. You can assign itemCount = 3;, but you cannot assign itemCount = 'three'; because text is not an int.

For straightforward local values, var itemCount = 2; and int itemCount = 2; give you the same type protection. The explicit form makes the type visible in the declaration; var lets the initial value communicate it. Use whichever makes the code clearer.

There is a separate choice to make: will this variable need a new value later? Both an explicit declaration such as int itemCount = 2; and a var declaration allow reassignment, provided the new value fits the variable’s type.



final permits one assignment

Sometimes a value should be set once and then left alone. Put final before either an inferred or an explicit type:

final label = 'First entry';
final String firstCategory = category;

Dart infers that label is a String; firstCategory states its type explicitly. Neither name can be assigned another value after its first assignment. For example, firstCategory = 'Other'; would be an error.

final and a type answer different questions. String says what kind of value belongs here? final says may this variable be assigned again? You can use them together when both facts are useful. Unlike a compile-time constant, a final variable can receive a value determined while the program runs—as firstCategory does when it receives the current value of category.

For a concise reference, read the opening examples and the final examples in Dart’s official Variables guide. The page also discusses const and more advanced variable features; you do not need those sections yet.

Variables

The official Dart language guide reinforces the distinction between an inferred type, an explicit type, and a variable that can be assigned only once.

At the top of “Variables,” read the opening examples, from the first var name declaration through the String name example. Focus on how both forms establish a type. Then go to “Final and const.” Read the final examples, starting with the paragraph about variables you do not intend to change and stopping after the error example that assigns 'Alice' to name. You can stop before the paragraph beginning “Use const for variables”; the rest of that section is beyond today’s goal.



Put the choices together

Create a file named variables.dart with this complete program:

void main() {
  String category = 'Food';
  var itemCount = 2;
  double estimatedCost = 12.5;
  bool isPlanned = true;

  final String firstCategory = category;

  category = 'Transport';
  itemCount = 3;
  estimatedCost = 18.0;

  print(firstCategory);
  print(category);
  print(itemCount);
  print(estimatedCost);
  print(isPlanned);
}

Save it and run dart run variables.dart from its folder. The output should be:

Food
Transport
3
18.0
true

Follow the order of assignments. firstCategory receives 'Food' when it is declared. Later, category receives 'Transport'; that does not assign a new value to firstCategory. Meanwhile, itemCount and estimatedCost change, but each keeps its original type.

If you want to observe Dart enforcing these rules, add one of the following lines inside main() and run the file:

itemCount = 'three';
firstCategory = 'Transport';

The first attempts to put text in an int variable. The second attempts to assign a final variable again. Remove the line afterward to restore the working program.



Where this takes you

An explicit type such as String or int states what kind of value a variable holds. var asks Dart to infer that type from the initial value; it does not remove type checking. Add final when the variable must not be reassigned, with or without an explicit type.

For now, printing each variable separately makes its value easy to inspect. Next, you’ll use string interpolation to place variable values inside a single, more useful output message.