官方说明是这样的:
If you never intend to change a variable, use
final
orconst
, either instead ofvar
or in addition to a type. A final variable can be set only once; a const variable is a compile-time constant. (Const variables are implicitly final.)
也就是说,final是完全和Java一样的含义,变量仅能被赋值一次;const是用作编译时常量,也就是声明时,变量所指向的空间就一定固定不能更改,比如const foo = [1,2,3]
,这样foo.add(3)
就会报错,因为foo所指向的List已经固定不能修改。
所以可以这样理解,fianl仅限制了变量不能被赋予新的值,但是内容可以变化;const什么都不能改变
const还可以应用于List或者对象,表示赋予给变量的对象不能变化。
void main(List<String> args) {
// 表示 [] 不能变化,但是foo不受约束,所以foo还是可以重新赋值
var foo = const [];
foo = [1, 2, 3];
print(foo);
// 运行出错,报错Cannot add to an unmodifiable list
const test = [1, 2, 3];
test.add(3);
print(test);
// 可以执行
final test_2 = [1, 2, 3];
test_2.add(3);
print(test_2);
}