DEV Community

Pedro Luz
Pedro Luz

Posted on

3 2

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More