相同点
二者都可以用来定义一个常量,如下所示:
const PI = 3.14159265;
print(PI);
final PI2 = 3.14;
print(PI2);不同点
先来比较两段代码。
final currentTime = new DateTime.now();
print(currentTime);这段代码运行是没有任何问题的,结果如下:
2019-07-01 17:58:23.197829我们将上面代码中的final改成const,如下:
const currentTime = new DateTime.now();
print(currentTime);此时程序报错了:
NormanDemo/002Demo.dart:18:23: Error: New expression is not a constant expression.
const currentTime = new DateTime.now();
^^^这是为什么呢?
const是编译时常量,const修饰的常量值在编译的时候需要确定。
final是运行时常量,它是惰性初始化,即在运行时第一次使用前才会进行初始化。
因此,如果常量值在编译的时候就已经确定,运行时也不会改变,那么使用const和final均可;如果常量值在运行的时候才会确定(比如调用一个方法来给常量赋值),那么就必须使用final,不可以使用const。