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';
相关推荐
Qin_jiangshan15 小时前
flutter和reactNative以及uniapp区别
flutter·react native·uni-app
旧时光_16 小时前
第5章:容器类组件 —— 5.1 填充(Padding)
flutter
renxhui16 小时前
Flutter 基础控件速查(面向 Android 开发者)
flutter
A懿轩A16 小时前
【2025版 OpenHarmony】 GitCode 口袋工具:Flutter + Dio 网路请求 打造随身的鸿蒙版 GitCode 搜索助手
windows·flutter·华为·鸿蒙·openharmony·开源鸿蒙
QuantumLeap丶16 小时前
《Flutter全栈开发实战指南:从零到高级》- 20 -主题与国际化
flutter·ios·前端框架
心随雨下16 小时前
Flutter动画系统详解
flutter
白茶三许17 小时前
【OpenHarmony】Flutter 本地存储全解析:从键值对到数据库
数据库·flutter·开源·openharmony·gitcode
晚霞的不甘18 小时前
Flutter 与开源鸿蒙(OpenHarmony)深度集成:从插件开发到分布式能力实战(续篇)
flutter·开源·harmonyos
晚霞的不甘18 小时前
Flutter 与开源鸿蒙(OpenHarmony)生态融合:从 UI 渲染到系统级能力调用的全链路开发范式
flutter·开源·harmonyos