根据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.
那么,dynamic
和 var
之间有什么区别?什么时候使用?
最佳答案
dynamic
是所有 Dart 对象的底层类型。在大多数情况下,您不需要显式使用它。
var
是一个关键字,意思是“我不关心这里的类型是什么”。 Dart 会将 var
关键字替换为初始化器类型,或者如果没有初始化器,则默认保留它 dynamic
。
如果您希望变量赋值在其生命周期内发生变化,请使用 var
:
var msg = "Hello world.";
msg = "Hello world again.";
如果您希望变量赋值在其生命周期内保持不变,请使用final
:
final msg = "Hello world.";
使用final
(自由地)将帮助您捕获无意中更改变量赋值的情况。
请注意,对于对象而言,final
和 const
之间存在细微差别。 final
不一定使对象本身不可变,而 const
则可以:
// 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"];
关于dart - Dart 中 "var"和 "dynamic"类型之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12416507/