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';
相关推荐
开心-开心急了1 天前
关于Flutter与Qt for python 的一些技术、开源、商用等问题
开发语言·python·qt·flutter
猫林老师1 天前
Flutter for HarmonyOS开发指南(四):国际化与本地化深度实践
flutter·华为·harmonyos
猫林老师2 天前
Flutter for HarmonyOS 开发指南(一):环境搭建与项目创建
flutter·华为·harmonyos
sunly_2 天前
Flutter:视频预览功能
javascript·flutter·音视频
勤劳打代码2 天前
条分缕析 —— 通过 Demo 深入浅出 Provider 原理
flutter·面试·dart
2501_915918412 天前
Flutter 加固方案对比与实战,多工具组合的跨平台安全体系(Flutter App 加固/IPA 成品混淆/Ipa Guard CLI/自动化安全流程)
安全·flutter·ios·小程序·uni-app·自动化·iphone
Bryce李小白2 天前
Flutter中mixing的原理及应用场景
flutter
_大学牲2 天前
从 0 到上架:用 Flutter 一天做一款功德木鱼
前端·flutter·apple
嚴寒2 天前
2025最终!Mac配置Flutter全平台开发环境完整指南(亲测有效)
前端·flutter
Bryce李小白3 天前
Flutter版本管理工具FVM
flutter