Flutter —— key 的原理

Flutter —— key 的原理


之前的文章中有的类故意没有写Key,那么这个Key有什么作用呢?今天来探究一下。

1. Key 的原理

  • key 本身是一个抽象类,有一个工厂构造方法创建ValueKey
  • 直接子类主要有:LocalKey 和 GlobalKey
  • GlobalKey:帮助我们访问某个Widget的信息
  • LocalKey:它用来区别哪个Element要保留,哪个Element要删除。diff 算法核心所在
    • ValueKey : 以值作为参数 (数字,字符串)
    • ObjectKey : 以对象作为参赛
    • LocalKey (创建唯一标识)

2. Key 的 探究

其实任何的Widget都是有key的,key是可以为空的。

png)

创建一个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,
      )
    );
  }
}

运行后显示:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值