Dart Basics

Declaring variables (final, var, const, dynamic)

There are several ways of declaring variables, and this can be done by using:

  • var
  • final
  • const
  • dynamic

Examples:

final String name = 'Darth Vader';

var colour = 'Blue';

dynamic isReal = false;

What is the diference between them?

Var

var allows us to defined a variable that can change its value over time. MUTABLE

var balance = 100.0;
balance = 300.0;

TIP: avoid has much as possible to use var.

In the case where you dont assign a value to the variable in the same line:

var myString;
myString = 'Darth Vader'; // <-- this variable will be set to `dynamic`

Instead of the above is better to give it the type:

String myString;
myString = 'Dart Vader'; // <-- variable will be of type String

Final

final means read-only (can only be set once), where it is defined. IMMUTABLE

final String gender = 'Male'; // <--  `final`variables need to be assigned in the same line.
gender = 'Female'; // <-- not possible will throw an error

TIP: prefer final to var whenever possible

NOTE: final variables need to be assigned in the same line.


Const

const defines a compile-time constant

TIP: const’s are very good for performance, since dart can optimise generated coded

TIP: Prefer to use const over final over var


Dynamic

dynamic allows us to opt-out of type safe features.

var x = 10;
x = true; // <--- not valid

dynamic y = 10; // <--- Dart.. trust me. I know what I'm doing.
y = true; // <--- VALID

NOTE: Only use dynamic in extreme cases when there is no alternative, or for specific use cases.