Dart is a type of safe language. Each variable declared in a dart must be assigned with type.

As you see, variables are declared in multiple ways, and the type variable is inferred using the value declared or type declared as seen below.

void main() {
  // declare using var
  var str = "welcome";
  //declare using type
  String str2 = "hello";
}

From the above example, two strings are declared and initialized. These are static types.

Sometimes, For example, variables are assigned during function calls, and not sure about what type of function, It can be any primitive type.

How to Declare dynamic variable?

Dynamic Variables are declared like normal variables in Dart. The default value for the dynamic type is null.

dynamic variable_name=11;
dynamic variable_name1=11.23;
dynamic variable_name2="abc";

In the above program.

  • Variables of dynamic are declared
  • a type of the variable is declared, It tells the value type to be stored.
  • since the type is dynamic, We can assign the int, double, and string types to them.

Here is an example, dynamic types hold multiple values of different types.

Once you declare a value with a specific, You are fine to reassign the variable with a different type

void main() {
  dynamic variable_name = 11;
  dynamic variable_name1 = 11.23;
  dynamic variable_name2 = "abc";
  print(variable_name.runtimeType); //int
  print(variable_name is int); //true
  print(variable_name is dynamic); //true

  ;
  print(variable_name1.runtimeType); //double
  print(variable_name1 is double); //true
  print(variable_name1 is dynamic); //true

  print(variable_name2.runtimeType); //String
  print(variable_name2 is String); //true
  print(variable_name2 is dynamic); //true

  // assign to different types
  variable_name1 = "abc1";
  print(variable_name1.runtimeType); //String
  print(variable_name1 is double); //false
  print(variable_name1 is dynamic); //true
}

Advantages with dynamic type

  • You can assign any type of value and the type is dynamic
  • It is fine to reassign with a different type
  • It provides full proofed type safety in Dart language