DEV Community

Cover image for Understanding var, dynamic const, final in Dart
Steve
Steve

Posted on

Understanding var, dynamic const, final in Dart

Introduction

When you are a beginner with Dart you could get lost in the understanding of the different keywords to create a variable. These variable types in Dart follow a set of rules (some common to other programming languages). This writing aims to provide these rules and to explain to beginners what are the differences between these.

What is var ?

varis a keyword allowing to create a variable without specifying a type. The type of the variable will therefore be determined according to the initial value of this variable.
Note that the type of the variable will be inferred only if you assign it a value at its declaration:

void main() {
  var a = 1;
  a = "salut"; // Will not compile

  var b;
  b = 2; // runtimeType is int
  b = "salut"; // runtimeType is String
}
Enter fullscreen mode Exit fullscreen mode

This happens because we are not assigning an initial value to our variable at it's declaration.

What is dynamic ?

When creating a variable using the dynamic keyword, the data type will depend on the variable this variable will contain :

void main() {
    dynamic myVar = 2;
    print("$myVar is of type ${myVar.runtimeType}");
    myVar = "Hello World";
    print("$myVar is of type ${myVar.runtimeType}");
}
Enter fullscreen mode Exit fullscreen mode

This will output:

2 is of type int
Hello World is of type String
Enter fullscreen mode Exit fullscreen mode

What is final ?

The final keyword allows you to create variables that can only be assigned once at runtime. This means they are immutable. This keyword is mostly used to create instance variables for a class.

What is const ?

You may use the const keyword to create constant values; these variables are implicitly final. The thing you have to take care of is that the value of this variable must be known at compile time :

void main() {
  var myValue = 2;
  const myConst = myValue; // Cannot compile
  const activityCount = 4; // Will compile
}
Enter fullscreen mode Exit fullscreen mode

myValue's variable is not known at compile time because it's type is infered, therefore Dart will need to determine the type of the variable before executing the code; note that changing myValue to a constant will actually my everything work.

For a more complete reference, consider reading the dart language tour.

Thank you for reading, don't hesitate to let me know if you have any suggestion.

Top comments (1)

Collapse
 
rinath profile image
rinath

final variables can only be initialized once, but it's fields can be changed. So, final variable are mutable, but not assignable