Dart 2 tutorial : Variables in dart with example

Variables in Dart :

For declaring a variable in dart, ‘var’ keyword is used. e.g. :

main(){
 var day = "Sunday";

 print(day);
}

It declared the variable day that will store one reference to the String object “Sunday”. I have mentioned it as object because everything you can create as a variable is an object in dart. Each object is an instance of a class and each class is inherited from the object class. Even functions and null are also objects. Instead of using var, we can also specify the type of the variable directly :

main(){
 String day = "Sunday";

 print(day);
}

If you will try to assign a different type to day, e.g. if you are trying to assign 2 to day, it will show you one warning message : Warning: A value of type ‘int’ cannot be assigned to a variable of type ‘String’.

Intial value of a variable in Dart :

As I have mentioned before, each variable is an object in Dart. So, all uninitialized variables have initial value of null.You can use assert(condition) to check if the value of a variable is null. assert(condition) is used to check a condition. It is used mainly for development time.On production code, it is ignored. If the condition is false, it throws one exception. For example :

main(){
 String day;

 assert(day != null,"value of day is null");
}

It will throw you one exception error, but you need to run this program with assert enabled. On Dart 2, you can use —enable-asserts flag to enable assert condition. If this program is saved in sample.dart file, then use dart —enable-asserts sample.dart to run it with assert. If we are not defining the type of an object, it is considered as dynamic type. Means, it can be of any type. Instead of var , we can also use dynamic to declare a variable :

main(){
  dynamic day;

  day = "Sunday";
  print(day);
}

Final and Const variables in dart :

Final and Const variables are constant variables. final and const keywords are used. It looks like both are same. To know the difference easily, let’s look at the below program :

main(){
  int three = 3;
  
  final nine = three * three;

  print(nine);
}

This program will execute and print 9 as output. But :

main(){
  int three = 3;
  
  const nine = three * three;

  print(nine);
}

It will throw you one compile time error that Const variables must be initialized with a constant value. The const keyword is used to declare a compile-time constant. const variables are actually implicitly final variables. So, to make the above program work, we need to declare three as a const variable, i.e. a compile time constant variable.

main(){
  const int three = 3;
  
  const nine = three * three;

  print(nine);
}

It will print 9 as output.