What's the Difference Between var and dynamic type in Dart

What’s the Difference Between var and dynamic type in Dart?

A dynamic variable can change its type and a var type can’t be changed. dynamic is a type underlying all Dart objects. So in this article, we will go through What’s the

Difference Between var and dynamic type in Dart.

In this blog post, we’ll delve into the differences between the var and dynamic types in Dart. As a Dart developer, it’s crucial to understand when and how to use these types effectively to ensure clean and maintainable code. We’ll explore the characteristics and behaviors of var and dynamic types, discussing their implications on type inference, static type checking, and code readability. You’ll gain insights into their usage scenarios, best practices, and potential pitfalls.

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 (literally) 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"];

var, like final, is used to declare a variable. It is not a type at all.

Dart is smart enough to know the exact type in most situations. For example, the following two statements are equivalent

String a = "abc"; // type of variable is String
var a = "abc";    // a simple and equivalent (and also recommended) way
                  // to declare a variable for string types

On the other hand, the dynamic is a special type indicating it can be any type (aka class).

For example, by casting an object to dynamic, you can invoke any method (assuming there is one).

(foo as dynamic).whatever(); //valid. compiler won't check if whatever() exists
(foo as var).whatever(); //illegal. var is not a type

Consider a code snippet like the below:

void main() {
  dynamic x = 'hal';
  x = 123;
  print(x);
  var a = 'hal';
  a = 123;
  print(a);
}

you can change the type of x, but not a. Consider a code snippet like the below:

var a ;
a = 123;
print(a is int);
print(a);
a = 'hal';
print(a is String);
When defined without initial value, var is dynamic
var b = 321;
print(b is int);
print(b);
//b = 'hal'; //error
print(b is String);

When defined with an initial value, var is int in this case.

  • dynamic: can change TYPE of the variable, & can change VALUE of the variable later in code.
  • var: can’t change TYPE of the variable, but can change the VALUE of the variable later in code.
  • final: can’t change TYPE of the variable, & can’t change VALUE of the variable later in code.

For example :

var myVar = 'hello';
dynamic myDynamicVar = 'hello';
myVar = 123; // not possible
myDynamicVar = 123; // possible

Both in dynamic and var, the variable can hold data of any data type, i.e., int, float, string, if a variable is declared as a dynamic and if even initialized, its type can change over time.

void main() {
  dynamic x = 'abc';
  x = 12345;
  print(x);

}

If you declare a variable as a var, once assigned type can not change.

void main() {
  var x = 'abc';
  x = 12345;
  print(x);
}

The above code will result in the error stating that A value of type ‘int‘ can’t be assigned to a variable of type ‘String‘ – line 3

BUT, if you state a var without initializing, it becomes a dynamic:

void main() {
  var x ;
  x = 'abc';
  x=12345;
  print(x);
}

If you use var you can’t change the data type of the variable. But if you use dynamic you can change it freely.

For example:

dynamic x = 12; // type: integer
x= "Hello world"; // type: string

This will work with no issues if you do the same using var instead of dynamic you will get an error since you can’t change the data type because it is automatically assigned to the variable when initialized.

Conclusion:

In this article, we have been through what’s the difference between 'var' and 'dynamic' types in Dart and how it is crucial for efficient coding and robust app development. At Flutter Agency, we specialize in helping developers master these essential concepts. As a leading mobile apps development agency, we offer expert guidance and resources to ensure your Dart programming is top-notch. Whether you’re a seasoned developer or just starting out, our team is here to support your journey towards creating high-quality mobile applications.

Keep Learning !!! Keep Fluttering !!!

Do let us know in the comments if you are still confused in flutter!!

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields