Flutter Key 小记
前置知识
Flutter 常见组件 & 三棵树:https://blog.woini.men/post/flutter-chang-jian-zu-jian-and-san-ke-shu/
局部键 (Local Key)
特点:仅与同级比较,速度快,开销小。在同级中必须具有唯一性。
- ValueKey:对比值是否相同(==)
- ObjectKey:对比对象是否为同一实例(Iidentical)
- UniqueKey:返回一个局部唯一的 Key。
实例
1AnimatedSwitcher(
2 duration: Duration(seconds: 1),
3 child: Text("$name", key: UniqueKey()),
4);
全局键 (Global Key)
特点:可通过其访问组件的 Element。必须具有全局唯一性。
实战应用
当有组件发生变动,如移除或交换时,Flutter 会尝试重新建立 Widget 与 Element 的关联,不能复用 Element 时才会销毁重建 Element。这是一种比较常见的优化机制。
重建关联依据
类型、Key(可选)
重建关联流程
- 对比类型 ✅ -》 对比 Key ✅ -》 建立关联(复用 Element)
- 对比类型 ✅ -》 对比 Key ❎ -》 搜索同级组件 -》 重新关联并调整 Element 在 Tree 中的位置 ✅ or 销毁 Element 后在 Tree 相应位置重新创建 Element ❎
- 对比类型 ❎ -》 搜索同级组件 -》 重新关联并调整 Element 在 Tree 中的位置 ✅ or 销毁 Element 后在 Tree 相应位置重新创建 Element ❎