
常量不仅仅是final变量的怪异版本,它会在梦中困扰着您所有与之相关的错误。Compile-time常量是提高应用程序性能的好方法,而无需多次创建同一对象,也可以说是在编译时“预创建”对象。
const还是final?
, , . , , const final . .
void run() {
const myConstNumber = 5;
final myFinalNumber = 5;
myConstNumber = 42;
myFinalNumber = 42;
}
final, const , . , const .
class MyClass {
final int myFinalField;
const int myConstField;
MyClass(this.myFinalField, this.myConstField);
}
, , final, const. , , (. ). ...
Dart . , "hello", , 3.14, , .
, .
void run() {
const myList = [1, 2, 3];
const myMap = {'one': 1};
const mySet = {1, 2, 3};
}
: , if, spread , .
, const final , , . Dart , , . .

, , , . , .
void run() {
final finalVariable = 123456;
const constVariable = 123456;
const notWorking = finalVariable;
const working = constVariable;
}
, – , , , ...
Flutter const , , EdgeInsets, . - , .
const EdgeInsets.all(8), . , const , .
, const . : final .
class MyConstClass {
final int field1;
final List<String> field2;
const MyConstClass(this.field1, this.field2);
}
void run() {
const constVariable = 123456;
const x = MyConstClass(constVariable, ['hello', 'there']);
}
, , const .
class MyWannabeConstClass {
final Future<int> field;
const MyWannabeConstClass(this.field);
}
void run() {
const x = MyWannabeConstClass(Future.value(123));
}
Dart , , , ""? , . const , . .
void run() {
final implicitNew = MyWannabeConstClass(Future.value(123));
final explicitNew = new MyWannabeConstClass(Future.value(123));
}
const , , , Flutter .
, const final .
, new , const .
void run() {
const implicitConst = MyConstClass(1);
const explicitConst = const MyConstClass(1);
}
const , , , .
void run() {
final regularVariable = const MyConstClass(1);
}
结论
希望本指南能够阐明const构造函数的含义,以及通常在Dart中的常量的含义。尝试尽可能使用const它,您将逐行在应用程序中进行较小的性能改进。而且,您知道通过少量改进它是如何发生的-它们给出了总体结果。