前言

在开发 Flutter 的过程中你可能会发现,一些小部件的构造函数中都有一个可选的参数——Key。刚接触的同学或许会对这个概念感到很迷茫,感到不知所措。
在这篇文章中我们会深入浅出的介绍什么是 Key,以及应该使用 key 的具体场景。

什么是Key

在 Flutter 中我们经常与状态打交道。我们知道 Widget 可以有 Stateful 和 Stateless 两种。Key 能够帮助开发者在 Widget tree 中保存状态,在一般的情况下,我们并不需要使用 Key。那么,究竟什么时候应该使用 Key呢。
我们来看看下面这个例子。

  1. class StatelessContainer extends StatelessWidget {
  2. final Color color = RandomColor().randomColor();
  3. @override
  4. Widget build(BuildContext context) {
  5. return Container(
  6. width: 100,
  7. height: 100,
  8. color: color,
  9. );
  10. }
  11. }

这是一个很简单的 Stateless Widget,显示在界面上的就是一个 100 * 100 的有颜色的 Container。 RandomColor 能够为这个 Widget 初始化一个随机颜色。
我们现在将这个Widget展示到界面上。

  1. class Screen extends StatefulWidget {
  2. @override
  3. _ScreenState createState() => _ScreenState();
  4. }
  5. class _ScreenState extends State<Screen> {
  6. List<Widget> widgets = [
  7. StatelessContainer(),
  8. StatelessContainer(),
  9. ];
  10. @override
  11. Widget build(BuildContext context) {
  12. return Scaffold(
  13. body: Center(
  14. child: Row(
  15. mainAxisAlignment: MainAxisAlignment.center,
  16. children: widgets,
  17. ),
  18. ),
  19. floatingActionButton: FloatingActionButton(
  20. onPressed: switchWidget,
  21. child: Icon(Icons.undo),
  22. ),
  23. );
  24. }
  25. switchWidget(){
  26. widgets.insert(0, widgets.removeAt(1));
  27. setState(() {});
  28. }
  29. }

这里在屏幕中心展示了两个 StatelessContainer 小部件,当我们点击 floatingActionButton 时,将会执行 switchWidget 并交换它们的顺序。
Flutter | 深入浅出熟悉的陌生人Key - 图1
看上去并没有什么问题,交换操作被正确执行了。现在我们做一点小小的改动,将这个 StatelessContainer 升级为 StatefulContainer。

  1. class StatefulContainer extends StatefulWidget {
  2. StatefulContainer({Key key}) : super(key: key);
  3. @override
  4. _StatefulContainerState createState() => _StatefulContainerState();
  5. }
  6. class _StatefulContainerState extends State<StatefulContainer> {
  7. final Color color = RandomColor().randomColor();
  8. @override
  9. Widget build(BuildContext context) {
  10. return Container(
  11. width: 100,
  12. height: 100,
  13. color: color,
  14. );
  15. }
  16. }

在 StatefulContainer 中,我们将定义 Color 和 build 方法都放进了 State 中。
现在我们还是使用刚才一样的布局,只不过把 StatelessContainer 替换成 StatefulContainer,看看会发生什么。
Flutter | 深入浅出熟悉的陌生人Key - 图2
这时,无论我们怎样点击,都再也没有办法交换这两个Container的顺序了,而 switchWidget 确实是被执行了的。
为了解决这个问题,我们在两个 Widget 构造的时候给它传入一个 UniqueKey。

  1. class _ScreenState extends State<Screen> {
  2. List<Widget> widgets = [
  3. StatefulContainer(key: UniqueKey(),),
  4. StatefulContainer(key: UniqueKey(),),
  5. ];
  6. ···

然后这两个 Widget 又可以正常被交换顺序了。
看到这里大家肯定心中会有疑问,为什么 Stateful Widget 无法正常交换顺序,加上了 Key 之后就可以了,在这之中到底发生了什么? 为了弄明白这个问题,我们将涉及 Widget 的 diff 更新机制。

分析问题

首先要知道Flutter中有三棵树,分别是==Widget Tree==、==Element Tree== 和 ==RenderObject Tree==。

  • Widget: Element 的配置信息。与Element的关系可以是一对多,一份配置可以创造多个Element实例。
  • Element:Widget 的实例化,内部持有Widget和RenderObject。
  • RenderObject:负责渲染绘制。

简单的比拟一下,Widget有点像是产品经理,规划产品整理需求。Element则是UI小姐姐,根据原型整理出最终设计图。RenderObject就是我们程序员,负责具体的落地实现。
代码中可以确定一点,两个方块的Widget肯定是交换了。既然Widget没有问题,那就看看Element。
但是为什么StatelessWidget可以成功,换成StatefulWidget就失效了?
点击按钮调用setState方法,依次执行:

  1. graph TB
  2. A["_element.markNeedsBuild()"] -- 标记自身元素dirty为true --> B["owner.scheduleBuildFor()"]
  3. B --添加至_dirtyElements--> D["drawFrame()"]
  4. D --> E["buildScope()"]
  5. E --> F["_dirtyElements[index].rebuild()"]
  6. F --> G["performRebuild()"]
  7. G --> H["updateChild()"]

我们重点看一下Element的updateChild方法:

  1. @protected
  2. Element updateChild(Element child, Widget newWidget, dynamic newSlot) {
  3. // 如果'newWidget'为null,而'child'不为null,那么我们删除'child',返回null。
  4. if (newWidget == null) {
  5. if (child != null)
  6. deactivateChild(child);
  7. return null;
  8. }
  9. if (child != null) {
  10. // 两个widget相同,位置不同更新位置,返回child。这里比较的是hashCode
  11. if (child.widget == newWidget) {
  12. if (child.slot != newSlot)
  13. updateSlotForChild(child, newSlot);
  14. return child;
  15. }
  16. // 我们的交换例子处理在这里
  17. if (Widget.canUpdate(child.widget, newWidget)) {
  18. if (child.slot != newSlot)
  19. updateSlotForChild(child, newSlot);
  20. child.update(newWidget);
  21. return child;
  22. }
  23. deactivateChild(child);
  24. }
  25. // 如果无法更新复用,那么创建一个新的Element并返回。
  26. return inflateWidget(newWidget, newSlot);
  27. }

Widget的canUpdate方法:

  1. static bool canUpdate(Widget oldWidget, Widget newWidget) {
  2. return oldWidget.runtimeType == newWidget.runtimeType
  3. && oldWidget.key == newWidget.key;
  4. }

这里出现了我们今天的主角Key,不过我们先放在一边。canUpdate方法的作用是判断newWidget是否可以替代oldWidget作为Element的配置。 一开始也提到了,Element会持有Widget。
该方法判断的依据就是runtimeType和key是否相等。在我们上面的例子中,不管是StatelessWidget还是StatefulWidget的方块,显然canUpdate都会返回true。因此执行child.update(newWidget)方法,就是将持有的Widget更新了。

不知道这里大家有没有注意到,这里并没有更新state。我们看一下StatefulWidget源码:

  1. abstract class StatefulWidget extends Widget {
  2. const StatefulWidget({ Key key }) : super(key: key);
  3. @override
  4. StatefulElement createElement() => StatefulElement(this);
  5. @protected
  6. State createState();
  7. }

StatefulWidget中创建的是StatefulElement,它是Element的子类。

  1. class StatefulElement extends ComponentElement {
  2. StatefulElement(StatefulWidget widget)
  3. : _state = widget.createState(),
  4. super(widget) {
  5. _state._element = this;
  6. _state._widget = widget;
  7. }
  8. @override
  9. Widget build() => state.build(this);
  10. State<StatefulWidget> get state => _state;
  11. State<StatefulWidget> _state;
  12. ...
  13. }

通过调用StatefulWidget的createElement方法,最终执行createState创建出state并持有。也就是说StatefulElement才持有state。
所以我们上面两个StatefulWidget的方块的交换,实际只是交换了“身体”,而“灵魂”没有交换。所以不管你怎么点击按钮都是没有变化的。

解决问题

找到了原因,那么怎么解决它?那就是设置一个不同的Key:

  1. class _ScreenState extends State<Screen> {
  2. List<Widget> widgets = [
  3. StatefulContainer(key: UniqueKey(),),
  4. StatefulContainer(key: UniqueKey(),),
  5. ];
  6. ···

但是这里要注意的是,这里不是说添加key以后,在canUpdate方法返回false,最后执行inflateWidget(newWidget, newSlot)方法创建新的Element。

  1. @protected
  2. Element inflateWidget(Widget newWidget, dynamic newSlot) {
  3. final Key key = newWidget.key;
  4. if (key is GlobalKey) {
  5. final Element newChild = _retakeInactiveElement(key, newWidget);
  6. if (newChild != null) {
  7. newChild._activateWithParent(this, newSlot);
  8. final Element updatedChild = updateChild(newChild, newWidget, newSlot);
  9. assert(newChild == updatedChild);
  10. return updatedChild;
  11. }
  12. }
  13. // 这里就调用到了createElement,重新创建了Element
  14. final Element newChild = newWidget.createElement();
  15. newChild.mount(this, newSlot);
  16. return newChild;
  17. }

如果如此,那么执行createElement方法势必会重新创建state,那么方块的颜色也就随机变了。当然此种情况并不是不存在,比如我们给现有的方块外包一层Padding(SingleChildRenderObjectElement):

  1. @override
  2. void initState() {
  3. super.initState();
  4. widgets = [
  5. Padding(
  6. padding: const EdgeInsets.all(8.0),
  7. child: StatefulColorfulTile(key: Key("1"),)
  8. ),
  9. Padding(
  10. padding: const EdgeInsets.all(8.0),
  11. child: StatefulColorfulTile(key: Key("2"),)
  12. ),
  13. ];
  14. }

这种情况下,交换后比较外层Padding不变,接着比较内层StatefulColorfulTile,因为key不相同导致颜色随机改变。因为两个方块位于不同子树,两者在逐层对比中用到的就是canUpdate方法返回false来更改。

而本例是方块的外层是Row(MultiChildRenderObjectElement),是对比两个List,存在不同。关键在于update时调用的RenderObjectElement.updateChildren方法。

  1. @protected
  2. List<Element> updateChildren(List<Element> oldChildren, List<Widget> newWidgets, { Set<Element> forgottenChildren }) {
  3. ...
  4. int newChildrenTop = 0;
  5. int oldChildrenTop = 0;
  6. int newChildrenBottom = newWidgets.length - 1;
  7. int oldChildrenBottom = oldChildren.length - 1;
  8. final List<Element> newChildren = oldChildren.length == newWidgets.length ?
  9. oldChildren : List<Element>(newWidgets.length);
  10. Element previousChild;
  11. // 从前往后依次对比,相同的更新Element,记录位置,直到不相等时跳出循环。
  12. while ((oldChildrenTop <= oldChildrenBottom) &&
  13. (newChildrenTop <= newChildrenBottom)) {
  14. final Element oldChild = replaceWithNullIfForgotten(oldChildren[oldChildrenTop]);
  15. final Widget newWidget = newWidgets[newChildrenTop];
  16. // 注意这里的canUpdate,本例中在没有添加key时返回true。
  17. // 因此直接执行updateChild,本循环结束返回newChildren。后面因条件不满足都在不执行。
  18. // 一旦添加key,这里返回false,不同之处就此开始。
  19. if (oldChild == null || !Widget.canUpdate(oldChild.widget, newWidget))
  20. break;
  21. final Element newChild = updateChild(oldChild, newWidget, previousChild);
  22. newChildren[newChildrenTop] = newChild;
  23. previousChild = newChild;
  24. newChildrenTop += 1;
  25. oldChildrenTop += 1;
  26. }
  27. // 从后往前依次对比,记录位置,直到不相等时跳出循环。
  28. while ((oldChildrenTop <= oldChildrenBottom) &&
  29. (newChildrenTop <= newChildrenBottom)) {
  30. final Element oldChild = replaceWithNullIfForgotten(oldChildren[oldChildrenBottom]);
  31. final Widget newWidget = newWidgets[newChildrenBottom];
  32. if (oldChild == null || !Widget.canUpdate(oldChild.widget, newWidget))
  33. break;
  34. oldChildrenBottom -= 1;
  35. newChildrenBottom -= 1;
  36. }
  37. // 至此,就可以得到新旧List中不同Weiget的范围。
  38. final bool haveOldChildren = oldChildrenTop <= oldChildrenBottom;
  39. Map<Key, Element> oldKeyedChildren;
  40. // 如果存在中间范围,扫描旧children,获取所有的key与Element保存至oldKeyedChildren。
  41. if (haveOldChildren) {
  42. oldKeyedChildren = <Key, Element>{};
  43. while (oldChildrenTop <= oldChildrenBottom) {
  44. final Element oldChild = replaceWithNullIfForgotten(oldChildren[oldChildrenTop]);
  45. if (oldChild != null) {
  46. if (oldChild.widget.key != null)
  47. oldKeyedChildren[oldChild.widget.key] = oldChild;
  48. else
  49. // 没有key就移除对应的Element
  50. deactivateChild(oldChild);
  51. }
  52. oldChildrenTop += 1;
  53. }
  54. }
  55. // 更新中间不同的部分
  56. while (newChildrenTop <= newChildrenBottom) {
  57. Element oldChild;
  58. final Widget newWidget = newWidgets[newChildrenTop];
  59. if (haveOldChildren) {
  60. final Key key = newWidget.key;
  61. if (key != null) {
  62. // key不为null,通过key获取对应的旧Element
  63. oldChild = oldKeyedChildren[key];
  64. if (oldChild != null) {
  65. if (Widget.canUpdate(oldChild.widget, newWidget)) {
  66. oldKeyedChildren.remove(key);
  67. } else {
  68. oldChild = null;
  69. }
  70. }
  71. }
  72. }
  73. // 本例中这里的oldChild.widget与newWidget hashCode相同,在updateChild中成功被复用。
  74. // ''' 此处的复用,解决了上面【只是交换了“身体”,而“灵魂”没有交换】的问题 '''
  75. final Element newChild = updateChild(oldChild, newWidget, previousChild);
  76. newChildren[newChildrenTop] = newChild;
  77. previousChild = newChild;
  78. newChildrenTop += 1;
  79. }
  80. // 重置
  81. newChildrenBottom = newWidgets.length - 1;
  82. oldChildrenBottom = oldChildren.length - 1;
  83. // 将后面相同的Element更新后添加到newChildren,至此形成新的完整的children。
  84. while ((oldChildrenTop <= oldChildrenBottom) &&
  85. (newChildrenTop <= newChildrenBottom)) {
  86. final Element oldChild = oldChildren[oldChildrenTop];
  87. final Widget newWidget = newWidgets[newChildrenTop];
  88. final Element newChild = updateChild(oldChild, newWidget, previousChild);
  89. newChildren[newChildrenTop] = newChild;
  90. previousChild = newChild;
  91. newChildrenTop += 1;
  92. oldChildrenTop += 1;
  93. }
  94. // 清除旧列表中多余的Element
  95. if (haveOldChildren && oldKeyedChildren.isNotEmpty) {
  96. for (Element oldChild in oldKeyedChildren.values) {
  97. if (forgottenChildren == null || !forgottenChildren.contains(oldChild))
  98. deactivateChild(oldChild);
  99. }
  100. }
  101. return newChildren;
  102. }

StatelessContainer 比较过程

在 StatelessContainer 中,我们并没有传入 key ,所以只比较它们的 runtimeType。这里 runtimeType 一致,canUpdate 方法返回 true,两个 Widget 被交换了位置,StatelessElement 调用新持有 Widget 的 build 方法重新构建,而我们的 color 实际上就是储存在 widget 中的,因此在屏幕上两个 Widget 便被正确的交换了顺序。

StatefulContainer 比较过程

而在 StatefulContainer 的例子中,我们将 color 的定义放在了 State 中,Widget 并不保存 State,真正 hold State 的引用的是 Stateful Element。
当我们没有给 Widget 任何 key 的时候,将会只比较这两个 Widget 的 runtimeType 。由于两个 Widget 的属性和方法都相同,canUpdate 方法将会返回 true,于是更新 StatefulWidget 的位置,这两个 Element 将不会交换位置。但是原有 Element 只会从它持有的 state 实例中 build 新的 widget。因为 element 没变,它持有的 state 也没变。所以颜色不会交换。这里变换 StatefulWidget 的位置是没有作用的。
而我们给 Widget 一个 key 之后,canUpdate 方法将会比较两个 Widget 的 runtimeType 以及 key。并返回 false。(这里 runtimeType 相同,key 不同)
此时 RenderObjectElement 会用新 Widget 的 key 在老 Element 列表里面查找,找到匹配的则会更新 Element 的位置并更新对应 renderObject 的位置,对于这个例子来讲就是交换了 Element 的位置并交换了对应 renderObject 的位置。都交换了,那么颜色自然也就交换了。
这里感谢ad6623对之前错误描述的指出。

参考资料


作者:Vadaski
链接:https://juejin.cn/post/6844903811870359559
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

作者:唯鹿
链接:https://juejin.cn/post/6844904085007630349
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。