如果不会改变变量, 那么使用 final 或者 const:
- final 变量只会被设置一次, 在运行时初始化
- const 变量是编译时常量
final name = 'Bob'; // Without a type annotationfinal String nickname = 'Bobby';const bar = 1000000; // Unit of pressure (dynes/cm2)const double atm = 1.01325 * bar; // Standard atmosphere
如果一个 const 变量是 class 层的, 那么必须使用 static const 来声明:
class A {static const a = 4;}
使用 const “创建”而非”声明” 一个值, :
var foo = const [];final bar = const [];const baz = []; // Equivalent to `const []`
以 const 创建的变量, 比如上面的 foo, 是可以赋新值的:
foo = [1, 2, 3]; // Was const []
在 dart 2.5 以后, 可以使用 type checks/casts (is 和 as), collection if, spread operators (… and …?) 创建 const:
- is: 类型检查
- as: 类型转换
- collection if: 如果 if 后的
()中的表达式为真, 那么才初始化
// Valid compile-time constants as of Dart 2.5.const Object i = 3; // Where i is a const Object with an int value...const list = [i as int]; // Use a typecast.const map = {if (i is int) i: "int"}; // Use is and collection if.const set = {if (list is List<int>) ...list}; // ...and a spread.
Lists, Maps, Classes 的创建 const 值请看对应章节.
创建 list 常量:
var constantList = const [1, 2, 3];// constantList[1] = 1; // Uncommenting this causes an error.
创建 Set 常量:
final constantSet = const {'fluorine','chlorine','bromine','iodine','astatine',};// constantSet.add('helium'); // Uncommenting this causes an error.
创建 Map 常量:
final constantMap = const {2: 'helium',10: 'neon',18: 'argon',};// constantMap[2] = 'Helium'; // Uncommenting this causes an error.
