Flutter —— key 的原理
之前的文章中有的类故意没有写Key,那么这个Key有什么作用呢?今天来探究一下。
1. Key 的原理
- key 本身是一个抽象类,有一个工厂构造方法创建ValueKey
- 直接子类主要有:LocalKey 和 GlobalKey
- GlobalKey:帮助我们访问某个Widget的信息
- LocalKey:它用来区别哪个Element要保留,哪个Element要删除。diff 算法核心所在
- ValueKey : 以值作为参数 (数字,字符串)
- ObjectKey : 以对象作为参赛
- LocalKey (创建唯一标识)
2. Key 的 探究
其实任何的Widget都是有key的,key是可以为空的。
创建一个KeyDemo放在MaterialApp的home里面
class KeyDemo extends StatefulWidget {
const KeyDemo({Key? key}) : super(key: key);
@override
_KeyDemoState createState() => _KeyDemoState();
}
class _KeyDemoState extends State<KeyDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('KeyDemo'),),
body: const Text('hello'),
);
}
}
接下来创建一个随机颜色的正方形带标题的小方块。
class StfulItem extends StatefulWidget {
const StfulItem(this.title,{Key? key}) : super(key: key);
final String title;
@override
_StfulItemState createState() => _StfulItemState();
}
class _StfulItemState extends State<StfulItem> {
final color = Color.fromRGBO(Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1.0);
@override
Widget build(BuildContext context) {
return Container(
width: 100,
height: 100,
child: Text(widget.title),
color: color,
);
}
}
在_KeyDemoState声明一个Widget数组放StfulItem,然后在将Widget数组设为body中row的children。
class _KeyDemoState extends State<KeyDemo> {
List<Widget> items = [StfulItem('1111'),StfulItem('2222'),StfulItem('3333')];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('KeyDemo'),),
body: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: items,
)
);
}
}
运行后显示: