Difference between “var” and “dynamic” type in Dar

2020-05-15 08:29发布

According to this article:

As you might know, dynamic (as it is now called) is the stand-in type when a static type annotation is not provided.

So, what is the difference between dynamic and var? When to use?

标签: dart
8条回答
太酷不给撩
2楼-- · 2020-05-15 09:21

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, 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
查看更多
一纸荒年 Trace。
3楼-- · 2020-05-15 09:28

A dynamic variable can change his type and a var type can't be changed.

For example :

var myVar = 'hello';
dynamic myDynamicVar = 'hello';
myVar = 123; // not possible
myDynamicVar = 123; // possible
查看更多
登录 后发表回答