Flutter渲染之通过demo了解Key的作用

1. 前言

之前看很多类的构造函数里面有一个可选参数 key,平时写代码过程中也没怎么用就忽视了,后来遇到一些问题才发现这个小小的 key 可是有大作用,因此决定好好研究下。看了一些文章都是分析源代码,写得不明不白,晦涩难懂,因此决定通过两个实际的小 demo 来讲述。看本文之前最好先看看 Flutter渲染之Widget、Element 和 RenderObject,这个是基础。

2. demo1--删除列表第一个cell

需求

一个列表里面有多行cell,点击按钮,每次删除第一个cell。

实现过程

这个需求可以说是非常简单,不多说,先搞一个表和按钮出来,根据以前的编程经验,将数据源里面第一个元素删掉,然后 reloadData 即可,小菜一碟。

class KeyDemo2Page extends StatefulWidget {
  @override
  _KeyDemo2PageState createState() => _KeyDemo2PageState();
}

class _KeyDemo2PageState extends State<KeyDemo2Page> {
  final List<String> _names = ["1", "2", "3", "4", "5", "6", "7"];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        centerTitle: true,
        title: Text("Key demo"),
      ),
      body: ListView(
        children: _names.map((item) {
          return KeyItemLessWidget(item);
        }).toList(),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.delete),
        onPressed: (){
          setState(() {
            _names.removeAt(0);
          });
        },
      ),
    );
  }
}

class KeyItemLessWidget extends StatelessWidget {
  final String name;
  final randColor = Color.fromARGB(255, Random().nextInt(256), Random().nextInt(256), Random().nextInt(256));
  KeyItemLessWidget(this.name);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(name, style: TextStyle(color: Colors.white, fontSize: 50),),
      height: 80,
      color: randColor,
    );
  }
}

我们的cell使用的是 StatelessWidget,里面随机创建了一个颜色,出来的界面如下所示。

界面确实如我们想象的一样,点击按钮才发现,结果完全不是我们想象的那个样子,每次点击按钮,cell 的个数确实减少了,但是 cell 的颜色都跟以前不一样了。

如果看过我之前写的那篇文章Flutter渲染之Widget、Element 和 RenderObject的话就很好理解了。点击按钮的时候会执行 setState, 然后会重新执行 build 方法,包括每个 cell 都会重新 build。而每个cell生成随机颜色的代码就在 build 里面,因此这里每次点击按钮都会重新改变 cell 颜色。

因此,为了解决每次点击按钮cell 颜色都改变的问题,需要将 cell 由 StatelessWidget 改为 StatefullWidget。将颜色保存在 State 里面,这样应该就不会改变了。cell 代码如下。

class KeyItemLessWidget extends StatefulWidget {
  final String name;

  KeyItemLessWidget(this.name);

  @override
  _KeyItemLessWidgetState createState() => _KeyItemLessWidgetState();
}

class _KeyItemLessWidgetState extends State<KeyItemLessWidget> {
  final randColor = Color.fromARGB(255, Random().nextInt(256), Random().nextInt(256), Random().nextInt(256));

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(widget.name, style: TextStyle(color: Colors.white, fontSize: 50),),
      height: 80,
      color: randColor,
    );
  }
}

结果跟我们预想的一致,cell 的颜色确实保持住了,cell 个数也减一了。但是这里又有问题了,点击按钮我们希望是删除第一个cell,也就是第一个数据,但是这里实际每次却是从头部开始删除数字,但是界面上删除的颜色却是从尾部删除的。这就很奇怪了,还是不满足我们的需求。

通过前面那篇文章了解了 Element 的作用以后也可以理解这个现象。cell 创建以后都会创建相应的 Element,Element 里面有对 Widget 和 State 的引用,颜色保存在 State 里面。每次点击按钮执行 setState,cell 重新创建,通过 canUpdate 方法判断 Element 是否要重建还是直接替换 Widget,canUpdate 方法如下

  /// Whether the `newWidget` can be used to update an [Element] that currently
  /// has the `oldWidget` as its configuration.
  ///
  /// An element that uses a given widget as its configuration can be updated to
  /// use another widget as its configuration if, and only if, the two widgets
  /// have [runtimeType] and [key] properties that are [operator==].
  ///
  /// If the widgets have no key (their key is null), then they are considered a
  /// match if they have the same type, even if their children are completely
  /// different.
  static bool canUpdate(Widget oldWidget, Widget newWidget) {
    return oldWidget.runtimeType == newWidget.runtimeType
        && oldWidget.key == newWidget.key;
  }

通过源码可以看出是通过比对类型和 key 来判断的。我们这里没有 key,类型相同,通过注释可以知道这种情况返回 true。因此只需要用新 widget 替代 Element 里面的老 Widget 即可。但是 Element 里面的 State 还在,我们之前的颜色还保存在里面,新创建的 Widget 还是使用的之前的 State,执行的也是这个 State 里面的 build 方法, 因此头部的颜色并没有删除,尾部那个 Element 发现其他 Element 都有 Widget 更新,自己是多余的,因此 Flutter 因此会将其 unmount。因此我们看到的现象就是数字是删除的头部,但是颜色却是删除的尾部。

为了解决因为 Element 复用导致的删除尾部颜色问题,我们这里需要让 canUpdate 返回 false,这样每次 Element 都会重新创建。因此就要使用 Key 了,代码如下。

class KeyDemo2Page extends StatefulWidget {
  @override
  _KeyDemo2PageState createState() => _KeyDemo2PageState();
}

class _KeyDemo2PageState extends State<KeyDemo2Page> {
  final List<String> _names = ["1", "2", "3", "4", "5", "6", "7"];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        centerTitle: true,
        title: Text("Key demo"),
      ),
      body: ListView(
        children: _names.map((item) {
          return KeyItemLessWidget(item, key: Key(item),);
        }).toList(),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.delete),
        onPressed: (){
          setState(() {
            _names.removeAt(0);
          });
        },
      ),
    );
  }
}

class KeyItemLessWidget extends StatefulWidget {
  final String name;

  KeyItemLessWidget(this.name, {Key key}): super(key: key);

  @override
  _KeyItemLessWidgetState createState() => _KeyItemLessWidgetState();
}

class _KeyItemLessWidgetState extends State<KeyItemLessWidget> {
  final randColor = Color.fromARGB(255, Random().nextInt(256), Random().nextInt(256), Random().nextInt(256));

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(widget.name, style: TextStyle(color: Colors.white, fontSize: 50),),
      height: 80,
      color: randColor,
    );
  }
}

这里注意几点

  1. 在 KeyItemLessWidget 加了构造方法
KeyItemLessWidget(this.name, {Key key}): super(key: key);
  1. 在创建对象的时候传入 key
return KeyItemLessWidget(item, key: Key(item),);

现在为止才是实现了最终的需求,跟原生开发的思路非常不同,过程值得好好理解,最后关键还是靠 key 出马才解决问题。

3. demo2--交换两个小部件

需求

点击按钮,交换两个 widget 的位置。

实现过程

实现思路,交换数据源数据位置,执行 setState 即可,代码如下

class KeyDemo1Page extends StatefulWidget {
  @override
  _KeyDemo1PageState createState() => _KeyDemo1PageState();
}

class _KeyDemo1PageState extends State<KeyDemo1Page> {

  List<Widget> tiles = [
    StatelessColorfulTile(),
    StatelessColorfulTile(),
  ];

  Widget _itemForRow(BuildContext context, int index) {
    return tiles[index];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        centerTitle: true,
        title: Text("Key demo"),
      ),
      body: Column(children: tiles,),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.delete),
        onPressed: (){
          setState(() {
            tiles.insert(1, tiles.removeAt(0));
          });
        },
      ),
    );
  }
}

class StatelessColorfulTile extends StatelessWidget {
  Color myColor = Color.fromARGB(255, Random().nextInt(256), Random().nextInt(256), Random().nextInt(256));

  @override
  Widget build(BuildContext context) {
    return Container(
        color: myColor,
        child: Padding(padding: EdgeInsets.all(70.0))
    );
  }
}

界面如下

 

这里widget 我们使用的是 StatelessWidget,结果跟我们想要的一样,点击按钮两个widget 成功交换位置。这里我们做一点改变,将方块改为 StatefulWidget 再来看看。代码如下。

class StatelessColorfulTile extends StatefulWidget {
  @override
  _StatelessColorfulTileState createState() => _StatelessColorfulTileState();
}

class _StatelessColorfulTileState extends State<StatelessColorfulTile> {
  Color myColor = Color.fromARGB(255, Random().nextInt(256), Random().nextInt(256), Random().nextInt(256));

  @override
  Widget build(BuildContext context) {
    return Container(
        color: myColor,
        child: Padding(padding: EdgeInsets.all(70.0))
    );
  }
}

结果就是点击按钮毫无反应。这是怎么回事?

还是那个道理,StatefulWidget 的 State 在 Element 里面,虽然 Widget 确实换了了位置,但是 Element 通过canUpdate 方法判断返回 true,因此 Element 只是将自己的 Element 引用进行了替换而已。重新执行之前 State 的build 方法,颜色也还是以前的颜色,因此看上去就是没有任何变化。

为了实现切换的目的,这时候又要使用 Key 了,完整代码如下。

class KeyDemo1Page extends StatefulWidget {
  @override
  _KeyDemo1PageState createState() => _KeyDemo1PageState();
}

class _KeyDemo1PageState extends State<KeyDemo1Page> {
  List<StatelessColorfulTile> tiles = [
    StatelessColorfulTile(key: UniqueKey(),),
    StatelessColorfulTile(key: UniqueKey(),),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        centerTitle: true,
        title: Text("Key demo"),
      ),
//      body: ListView(
//        children:tiles,
//      ),
      body: Column(children: tiles,),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.delete),
        onPressed: (){
          setState(() {
            tiles.insert(1, tiles.removeAt(0));
          });
        },
      ),
    );
  }
}

class StatelessColorfulTile extends StatefulWidget {
  StatelessColorfulTile({Key key}): super(key: key);

  @override
  _StatelessColorfulTileState createState() => _StatelessColorfulTileState();
}

class _StatelessColorfulTileState extends State<StatelessColorfulTile> {
  Color myColor = Color.fromARGB(255, Random().nextInt(256), Random().nextInt(256), Random().nextInt(256));

  @override
  Widget build(BuildContext context) {
    return Container(
        color: myColor,
        child: Padding(padding: EdgeInsets.all(70.0))
    );
  }
}

这里使用了 UniqueKey(),作用后面分析。结果成功切换,实现我们提出的需求。

4. Key 的分类

key 的集成关系如上图,key 本身是一个抽象类。key 的定义如下

abstract class Key {
  /// Construct a [ValueKey<String>] with the given [String].
  ///
  /// This is the simplest way to create keys.
  const factory Key(String value) = ValueKey<String>;

  /// Default constructor, used by subclasses.
  ///
  /// Useful so that subclasses can call us, because the [new Key] factory
  /// constructor shadows the implicit constructor.
  @protected
  const Key.empty();
}

它有一个工厂构造器,创建出来一个 ValueKey,Key 直接子类主要有: LocalKey 和 GlobalKey。

4.1 LocakKey

它应用于具有相同父 Element 的 Widget 进行比较,也是 diff 算法的核心所在。他有三个子类:ValueKey、ObjectKey、UniqueKey。

• ValueKey:当我们以特定的值作为 key 时使用,比如一个字符串、数字等;
• ObjectKey:如果两个学生,他们的名字一样没使用 name 作为他们的 key 就不合适了,我们可以创建出一个学生对象,使用对象来作为 key。
• UniqueKey:我们要确保 key 的唯一性,可以使用 UniqueKey。如果希望强制刷新,每次 Element 都重新创建,那么可以使用 UniqueKey。

4.2 GlobalKey

GlobalKey 使用了一个静态常量 Map 来保存它对于的 Element,可以通过 GlobalKey 找到持有该 GlobalKey 的 Widget、State 和 Element。如下图自动提示信息。

比如上面 demo1 里面,我们可以使用 GlobalKey,在点击按钮的时候,打印出每个 cell 的name 属性。完整代码如下

class KeyDemo2Page extends StatefulWidget {
  @override
  _KeyDemo2PageState createState() => _KeyDemo2PageState();
}

class _KeyDemo2PageState extends State<KeyDemo2Page> {
  final List<String> _names = ["1", "2", "3", "4", "5", "6", "7"];
  final GlobalKey<_KeyItemLessWidgetState> globalKeyTest = GlobalKey();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.blue,
        centerTitle: true,
        title: Text("Key demo"),
      ),
      body: KeyItemLessWidget("哈啰出行", key: globalKeyTest,),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.delete),
        onPressed: (){
          print(globalKeyTest.currentState.widget.name);
        },
      ),
    );
  }
}

class KeyItemLessWidget extends StatefulWidget {
  final String name;
  KeyItemLessWidget(this.name, {Key key}): super(key: key);

  @override
  _KeyItemLessWidgetState createState() => _KeyItemLessWidgetState();
}

class _KeyItemLessWidgetState extends State<KeyItemLessWidget> {
  final randColor = Color.fromARGB(255, Random().nextInt(256), Random().nextInt(256), Random().nextInt(256));

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text(widget.name, style: TextStyle(color: Colors.white, fontSize: 50),),
      height: 80,
      color: randColor,
    );
  }
}

注意:GlobalKey 是非常昂贵的,需要谨慎使用。

5. 总结

本文通过两个简单的 demo 引入了key,可以了解 key 的重要作用,需要深入了解 key 还需要看之前那篇文章 Flutter渲染之Widget、Element 和 RenderObject,首先知道 Widget、Element 和 RenderObject 的联系,这个是基础。体会到了 Key 的作用以后然后从代码层面对 Key 进行分类,便于系统掌握,最后还是一个小 demo 了解 GlobalKey 的作用。总的来说本文没有讲太多源码相关内容,尽量通过实际需求按理来一步一步讲解,很容易明白。

demo2--交换两个小部件 里面有个问题另外写了一篇文章可以看看ListView 的一个容易忽略的知识点

 



作者:黑化肥发灰
链接:https://www.jianshu.com/p/25aa9294acc5
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值