There is a post on dart's website and it explains it pretty well.个
Final:
"final"指单个赋值:final变量或字段must具有初始值设定项.一旦赋值,最终变量的值就不能更改.最终修改为variables.
Const:
"const"在DART中有一个更为复杂和微妙的含义.常量修改为values.您可以在创建集合(如const[1,2,3])和构造对象(而不是新建)(如const Point(2,3))时使用它.在这里,const意味着对象的整个深层状态可以在编译时完全确定,并且对象将被冻结并且完全不可变.
Const对象有几个有趣的属性和限制:
它们必须从可以在编译时计算的数据创建.常量对象无权访问您在运行时需要计算的任何内容.1+2是有效的常量表达式,但new DateTime.now()不是.
它们是深刻的、可传递的不可改变的.如果有包含集合的最后一个字段,则该集合仍然可以是可变的.如果您有一个常量集合,那么其中的所有内容也必须是常量,递归地.
他们是canonicalized岁.这有点像字符串插入:对于任何给定的常量值,无论常量表达式计算多少次,都将创建并重用单个常量对象.
Const:
If the value you have is computed at runtime (new DateTime.now()
, for example), you can not use a const for it. However, if the value is known at compile time (const a = 1;
), then you should use const
over final
. There are 2 other large differences between const
and final
. Firstly, if you're using const
, you have to declare it as static const
rather than just const
. Secondly, if you have a const
collection, everything inside of that is in const
. If you have a final
collection, everything inside of that is not final
.
Final:
final
should be used over const
if you don't know the value at compile time, and it will be calculated/grabbed at runtime. If you want an HTTP response that can't be changed, if you want to get something from a database, or if you want to read from a local file, use final
. Anything that isn't known at compile time should be final
over const
.
尽管如此,const
和final
都不能被重新分配,但是final
对象中的字段,只要它们本身不是const
或final
,就可以被重新分配(与const
不同).