只能被定义一次,并且不可修改的值叫做常量。
在 Flutter
中有两种常量修饰方法
final
const
final String a = '123';
final a = '123';
const String a = '123';
const a = '123';
final a = '123';
a = 'abc'; // 错误
const a = '123';
a = 'abc'; // 错误
final var a = '123'; // 错误
const var a = '123'; // 错误
final dt = DateTime.now();
const dt = const DateTime.now();
final
修饰时间可以是即时时间。即当前值会根据运行时进行变化const
修饰时间必需为确定值,即当前值不会根据运行时变化。final List ls = [11, 22, 33];
ls[1] = 44;
const List ls = [11, 22, 33];
ls[1] = 44; // 报错
final
修饰数组集合时,数组内的值可修改const
修饰数组集合时,数组内的值不可修改final a1 = [11, 22];
final a2 = [11, 22];
print(identical(a1, a2)); // false
const a1 = [11, 22];
const a2 = [11, 22];
print(identical(a1, a2)); // true
identical
通过比较两个引用的是否是同一个对象判断是否相等final
成员变量初始class PlaceholdWidget extends StatelessWidget {
final String? assetImagePath;
const PlaceholdWidget({
Key? key,
this.assetImagePath,
}) : super(key: key);
@override
Widget build(BuildContext context) {
...
}
}
const
全局参数// 本地存储key
static const storageFirstOpen = 'first_open';
static const storageLanguageCode = 'language_code';
static const storageThemeCode = 'theme_code';
static const storageToken = 'token';
static const StorageProfile = 'profile';