Flutter ☞ 常量

常量

只能被定义一次,并且不可修改的值叫做常量。

Flutter 中有两种常量修饰方法

  • final
  • const

相同点

类型声明可以省略

kotlin 复制代码
final String a = '123';
final a = '123';

const String a = '123';
const a = '123';

初始化后不能再赋值

kotlin 复制代码
final a = '123';
a = 'abc'; // 错误

const a = '123';
a = 'abc'; // 错误

不能和 var 同时使用

kotlin 复制代码
final var a = '123'; // 错误
const var a = '123'; // 错误

不同点

确定的值

kotlin 复制代码
final dt = DateTime.now();
const dt = const DateTime.now();
  • final 修饰时间可以是即时时间。即当前值会根据运行时进行变化
  • const 修饰时间必需为确定值,即当前值不会根据运行时变化。

不可变,可传递

kotlin 复制代码
final List ls = [11, 22, 33];
ls[1] = 44;

const List ls = [11, 22, 33];
ls[1] = 44; // 报错
  • final 修饰数组集合时,数组内的值可修改
  • const 修饰数组集合时,数组内的值不可修改

内存中重复创建

kotlin 复制代码
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 成员变量初始

kotlin 复制代码
class PlaceholdWidget extends StatelessWidget {
	final String? assetImagePath;
	
	const PlaceholdWidget({
		Key? key,
		this.assetImagePath,
	}) : super(key: key);

	@override
	Widget build(BuildContext context) {
		...
	}
}

const 全局参数

kotlin 复制代码
// 本地存储key
static const storageFirstOpen = 'first_open';
static const storageLanguageCode = 'language_code';
static const storageThemeCode = 'theme_code';
static const storageToken = 'token';
static const StorageProfile = 'profile';
相关推荐
helloxmg7 小时前
鸿蒙harmonyos next flutter通信之MethodChannel获取设备信息
flutter
helloxmg8 小时前
鸿蒙harmonyos next flutter混合开发之开发package
flutter·华为·harmonyos
lqj_本人1 天前
flutter_鸿蒙next_Dart基础②List
flutter
lqj_本人1 天前
flutter_鸿蒙next_Dart基础①字符串
flutter
The_tuber_sadness1 天前
【Flutter】- 基础语法
flutter
helloxmg1 天前
鸿蒙harmonyos next flutter通信之BasicMessageChannel获取app版本号
flutter
linpengteng2 天前
使用 Flutter 开发数字钱包应用(Dompet App)
前端·flutter·firebase
云兮Coder2 天前
鸿蒙 HarmonyNext 与 Flutter 的异同之处
flutter·华为·harmonyos