Difference between “var” and “dynamic” type in Dart?

dynamic is a type underlying all Dart objects. You shouldn’t need to explicitly use it in most cases.

var is a keyword, meaning “I don’t care to notate what the type is here.” Dart will replace the var keyword with the initializer type, or leave it dynamic by default if there is no initializer.

Use var if you expect a variable assignment to change during its lifetime:

var msg = "Hello world.";
msg = "Hello world again.";

Use final if you expect a variable assignment to remain the same during its lifetime:

final msg = "Hello world.";

Using final (liberally) will help you catch situations where you accidentally change the assignment of a variable when you didn’t mean to.

Note that there is a fine distinction between final and const when it comes to objects. final does not necessarily make the object itself immutable, whereas const does:

// can add/remove from this list, but cannot assign a new list to fruit.
final fruit = ["apple", "pear", "orange"];
fruit.add("grape");

// cannot mutate the list or assign a new list to cars.
final cars = const ["Honda", "Toyota", "Ford"];

// const requires a constant assignment, whereas final will accept both:
const names = const ["John", "Jane", "Jack"];

Leave a Comment