3
【笔记】Flutter 的 Key
source link: https://loli.fj.cn/2023/08/16/Flutter%E7%9A%84Key/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Flutter 通过不重复的 Key 作为唯一标识,来保存组件的状态和顺序
LocalKey 局部键
- 只在组件内有效
ValueKey
- 手动定义标识
<key>
:自定义字符串作为标识
Box(key: ValueKey("<key>"));
UniqueKey
- 由程序自动定义随机的标识
Box(key: UniqueKey());
ObjectKey
- 通过传递对象,将对象的地址作为键
<obj>
:任意对象
Box(key: ObjectKey(<obj>));
GlobalKey 全局键
- 在全局有效
定义全局 Key
GlobalKey globalKey = GlobalKey();
使用全局 Key
Box(key: globalKey);
获取子组件的 State
var boxState = globalKey.currentState as BoxState;
获取子组件 State 的属性值
boxState.属性名;
修改子组件 State 的属性值
boxState.属性名 = 值;
调用子组件 State 的方法
boxState.方法名();
获取子组件的 Widget
var boxWidget = globalKey.currentWidget as Box;
获取子组件 Widget 的属性
boxWidget.属性名;
获取子组件的 Context
var renderBox = globalKey.currentContext!.findRenderObject() as RenderBox;
获取子组件 Context 的属性
renderBox.属性名;
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK