DMarlon Studio

Lesson 2 · 2 of 20

var, final, const and types · Dart

Declare Dart variables with their type (String, int, double, bool), with var, final and const, and check each value's type with runtimeType.

Dart · var, final, const and types in DMarlon Studio: the example's code and its output in the terminal

A variable stores a value under a name. In Dart the type comes first and then the name: String city = 'Valencia';. The basic types are String (text), int (whole numbers), double (numbers with decimals) and bool (true or false).

Inside a string, `$name` inserts the variable's value: '$city has $population people' prints Valencia has 800000 people. This is the usual way to build text in Dart; lesson 4 covers it in depth.

With `var` you do not have to write the type: Dart works it out from the first value. var visitors = 1200; creates an int that can change later (visitors = visitors + 300), but it will always be an int: assigning 'many' to it is an error Dart catches before running anything.

`final` gives a value just once: mayor cannot change afterwards. `const` is stricter still: the value must be known before the program runs, like the 50 in speedLimit. Use final or const whenever a value will not change; the code is clearer and safer.

The commented-out assignments show errors on purpose: remove the slashes and Dart will not compile. At the end, `runtimeType` tells the type of each value: String, int, double and bool.

Code · main.dart

void main() {  // The type goes before the name: String, int, double, bool.  String city = 'Valencia';  int population = 800000;  double temperature = 22.5;  bool byTheSea = true;  // $name puts a variable inside the text.  print('$city has $population people');  print('Today: $temperature degrees. By the sea? $byTheSea');  // var lets Dart work out the type from the first value.  var visitors = 1200;  visitors = visitors + 300;  print('Visitors: $visitors');  // visitors = 'many';  // Error: visitors is an int.  // final: given a value once, it can never change.  final mayor = 'Elena Ruiz';  // const: a fixed value, known before the program runs.  const speedLimit = 50;  // speedLimit = 60;  // Error: a const cannot change.  print('Mayor: $mayor. Speed limit: $speedLimit km/h');  // runtimeType tells the type of a value.  print(city.runtimeType);  print(visitors.runtimeType);  print(temperature.runtimeType);  print(byTheSea.runtimeType);}

Output · dart run main.dart

Valencia has 800000 people
Today: 22.5 degrees. By the sea? true
Visitors: 1500
Mayor: Elena Ruiz. Speed limit: 50 km/h
String
int
double
bool

Key points

  • Type, then name: int age = 29;.
  • var infers the type, which then stays fixed.
  • final is set once; const is fixed at compile time.
  • $name puts a variable inside the text.
  • runtimeType tells the type of a value.

Exercise

Add a final variable with the name of a river and a const with its length in kilometres, and print a sentence with both plus the type of each.