DEV Community

Pedro Luz
Pedro Luz

Posted on

Dart basics - Variables

original posted here: https://pedromsluz.com/posts/2022/dart-basics/

There are several ways of declaring variables. This can be done using one of:

  • var
  • final
  • const
  • dynamic

Examples:

final String name = 'Darth Vader';

var colour = 'Blue';

dynamic isReal = false;
Enter fullscreen mode Exit fullscreen mode

What is the diference between them?

Var

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

var balance = 100.0;
balance = 300.0;
Enter fullscreen mode Exit fullscreen mode

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`
Enter fullscreen mode Exit fullscreen mode

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

String myString;
myString = 'Dart Vader'; // <-- variable will be of type String
Enter fullscreen mode Exit fullscreen mode

Final

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

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

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
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)