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 的一个容易忽略的知识点

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容