前言
在开发 Flutter 的过程中你可能会发现,一些小部件的构造函数中都有一个可选的参数——Key。刚接触的同学或许会对这个概念感到很迷茫,感到不知所措。
在这篇文章中我们会深入浅出的介绍什么是 Key,以及应该使用 key 的具体场景。
什么是Key
在 Flutter 中我们经常与状态打交道。我们知道 Widget 可以有 Stateful 和 Stateless 两种。Key 能够帮助开发者在 Widget tree 中保存状态,在一般的情况下,我们并不需要使用 Key。那么,究竟什么时候应该使用 Key呢。
我们来看看下面这个例子。
class StatelessContainer extends StatelessWidget {final Color color = RandomColor().randomColor();@overrideWidget build(BuildContext context) {return Container(width: 100,height: 100,color: color,);}}
这是一个很简单的 Stateless Widget,显示在界面上的就是一个 100 * 100 的有颜色的 Container。 RandomColor 能够为这个 Widget 初始化一个随机颜色。
我们现在将这个Widget展示到界面上。
class Screen extends StatefulWidget {@override_ScreenState createState() => _ScreenState();}class _ScreenState extends State<Screen> {List<Widget> widgets = [StatelessContainer(),StatelessContainer(),];@overrideWidget build(BuildContext context) {return Scaffold(body: Center(child: Row(mainAxisAlignment: MainAxisAlignment.center,children: widgets,),),floatingActionButton: FloatingActionButton(onPressed: switchWidget,child: Icon(Icons.undo),),);}switchWidget(){widgets.insert(0, widgets.removeAt(1));setState(() {});}}
这里在屏幕中心展示了两个 StatelessContainer 小部件,当我们点击 floatingActionButton 时,将会执行 switchWidget 并交换它们的顺序。
看上去并没有什么问题,交换操作被正确执行了。现在我们做一点小小的改动,将这个 StatelessContainer 升级为 StatefulContainer。
class StatefulContainer extends StatefulWidget {StatefulContainer({Key key}) : super(key: key);@override_StatefulContainerState createState() => _StatefulContainerState();}class _StatefulContainerState extends State<StatefulContainer> {final Color color = RandomColor().randomColor();@overrideWidget build(BuildContext context) {return Container(width: 100,height: 100,color: color,);}}
在 StatefulContainer 中,我们将定义 Color 和 build 方法都放进了 State 中。
现在我们还是使用刚才一样的布局,只不过把 StatelessContainer 替换成 StatefulContainer,看看会发生什么。
这时,无论我们怎样点击,都再也没有办法交换这两个Container的顺序了,而 switchWidget 确实是被执行了的。
为了解决这个问题,我们在两个 Widget 构造的时候给它传入一个 UniqueKey。
class _ScreenState extends State<Screen> {List<Widget> widgets = [StatefulContainer(key: UniqueKey(),),StatefulContainer(key: UniqueKey(),),];···
然后这两个 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方法,依次执行:
graph TBA["_element.markNeedsBuild()"] -- 标记自身元素dirty为true --> B["owner.scheduleBuildFor()"]B --添加至_dirtyElements--> D["drawFrame()"]D --> E["buildScope()"]E --> F["_dirtyElements[index].rebuild()"]F --> G["performRebuild()"]G --> H["updateChild()"]
我们重点看一下Element的updateChild方法:
@protectedElement updateChild(Element child, Widget newWidget, dynamic newSlot) {// 如果'newWidget'为null,而'child'不为null,那么我们删除'child',返回null。if (newWidget == null) {if (child != null)deactivateChild(child);return null;}if (child != null) {// 两个widget相同,位置不同更新位置,返回child。这里比较的是hashCodeif (child.widget == newWidget) {if (child.slot != newSlot)updateSlotForChild(child, newSlot);return child;}// 我们的交换例子处理在这里if (Widget.canUpdate(child.widget, newWidget)) {if (child.slot != newSlot)updateSlotForChild(child, newSlot);child.update(newWidget);return child;}deactivateChild(child);}// 如果无法更新复用,那么创建一个新的Element并返回。return inflateWidget(newWidget, newSlot);}
Widget的canUpdate方法:
static bool canUpdate(Widget oldWidget, Widget newWidget) {return oldWidget.runtimeType == newWidget.runtimeType&& oldWidget.key == newWidget.key;}
这里出现了我们今天的主角Key,不过我们先放在一边。canUpdate方法的作用是判断newWidget是否可以替代oldWidget作为Element的配置。 一开始也提到了,Element会持有Widget。
该方法判断的依据就是runtimeType和key是否相等。在我们上面的例子中,不管是StatelessWidget还是StatefulWidget的方块,显然canUpdate都会返回true。因此执行child.update(newWidget)方法,就是将持有的Widget更新了。
不知道这里大家有没有注意到,这里并没有更新state。我们看一下StatefulWidget源码:
abstract class StatefulWidget extends Widget {const StatefulWidget({ Key key }) : super(key: key);@overrideStatefulElement createElement() => StatefulElement(this);@protectedState createState();}
StatefulWidget中创建的是StatefulElement,它是Element的子类。
class StatefulElement extends ComponentElement {StatefulElement(StatefulWidget widget): _state = widget.createState(),super(widget) {_state._element = this;_state._widget = widget;}@overrideWidget build() => state.build(this);State<StatefulWidget> get state => _state;State<StatefulWidget> _state;...}
通过调用StatefulWidget的createElement方法,最终执行createState创建出state并持有。也就是说StatefulElement才持有state。
所以我们上面两个StatefulWidget的方块的交换,实际只是交换了“身体”,而“灵魂”没有交换。所以不管你怎么点击按钮都是没有变化的。
解决问题
找到了原因,那么怎么解决它?那就是设置一个不同的Key:
class _ScreenState extends State<Screen> {List<Widget> widgets = [StatefulContainer(key: UniqueKey(),),StatefulContainer(key: UniqueKey(),),];···
但是这里要注意的是,这里不是说添加key以后,在canUpdate方法返回false,最后执行inflateWidget(newWidget, newSlot)方法创建新的Element。
@protectedElement inflateWidget(Widget newWidget, dynamic newSlot) {final Key key = newWidget.key;if (key is GlobalKey) {final Element newChild = _retakeInactiveElement(key, newWidget);if (newChild != null) {newChild._activateWithParent(this, newSlot);final Element updatedChild = updateChild(newChild, newWidget, newSlot);assert(newChild == updatedChild);return updatedChild;}}// 这里就调用到了createElement,重新创建了Elementfinal Element newChild = newWidget.createElement();newChild.mount(this, newSlot);return newChild;}
如果如此,那么执行createElement方法势必会重新创建state,那么方块的颜色也就随机变了。当然此种情况并不是不存在,比如我们给现有的方块外包一层Padding(SingleChildRenderObjectElement):
@overridevoid initState() {super.initState();widgets = [Padding(padding: const EdgeInsets.all(8.0),child: StatefulColorfulTile(key: Key("1"),)),Padding(padding: const EdgeInsets.all(8.0),child: StatefulColorfulTile(key: Key("2"),)),];}
这种情况下,交换后比较外层Padding不变,接着比较内层StatefulColorfulTile,因为key不相同导致颜色随机改变。因为两个方块位于不同子树,两者在逐层对比中用到的就是canUpdate方法返回false来更改。
而本例是方块的外层是Row(MultiChildRenderObjectElement),是对比两个List,存在不同。关键在于update时调用的RenderObjectElement.updateChildren方法。
@protectedList<Element> updateChildren(List<Element> oldChildren, List<Widget> newWidgets, { Set<Element> forgottenChildren }) {...int newChildrenTop = 0;int oldChildrenTop = 0;int newChildrenBottom = newWidgets.length - 1;int oldChildrenBottom = oldChildren.length - 1;final List<Element> newChildren = oldChildren.length == newWidgets.length ?oldChildren : List<Element>(newWidgets.length);Element previousChild;// 从前往后依次对比,相同的更新Element,记录位置,直到不相等时跳出循环。while ((oldChildrenTop <= oldChildrenBottom) &&(newChildrenTop <= newChildrenBottom)) {final Element oldChild = replaceWithNullIfForgotten(oldChildren[oldChildrenTop]);final Widget newWidget = newWidgets[newChildrenTop];// 注意这里的canUpdate,本例中在没有添加key时返回true。// 因此直接执行updateChild,本循环结束返回newChildren。后面因条件不满足都在不执行。// 一旦添加key,这里返回false,不同之处就此开始。if (oldChild == null || !Widget.canUpdate(oldChild.widget, newWidget))break;final Element newChild = updateChild(oldChild, newWidget, previousChild);newChildren[newChildrenTop] = newChild;previousChild = newChild;newChildrenTop += 1;oldChildrenTop += 1;}// 从后往前依次对比,记录位置,直到不相等时跳出循环。while ((oldChildrenTop <= oldChildrenBottom) &&(newChildrenTop <= newChildrenBottom)) {final Element oldChild = replaceWithNullIfForgotten(oldChildren[oldChildrenBottom]);final Widget newWidget = newWidgets[newChildrenBottom];if (oldChild == null || !Widget.canUpdate(oldChild.widget, newWidget))break;oldChildrenBottom -= 1;newChildrenBottom -= 1;}// 至此,就可以得到新旧List中不同Weiget的范围。final bool haveOldChildren = oldChildrenTop <= oldChildrenBottom;Map<Key, Element> oldKeyedChildren;// 如果存在中间范围,扫描旧children,获取所有的key与Element保存至oldKeyedChildren。if (haveOldChildren) {oldKeyedChildren = <Key, Element>{};while (oldChildrenTop <= oldChildrenBottom) {final Element oldChild = replaceWithNullIfForgotten(oldChildren[oldChildrenTop]);if (oldChild != null) {if (oldChild.widget.key != null)oldKeyedChildren[oldChild.widget.key] = oldChild;else// 没有key就移除对应的ElementdeactivateChild(oldChild);}oldChildrenTop += 1;}}// 更新中间不同的部分while (newChildrenTop <= newChildrenBottom) {Element oldChild;final Widget newWidget = newWidgets[newChildrenTop];if (haveOldChildren) {final Key key = newWidget.key;if (key != null) {// key不为null,通过key获取对应的旧ElementoldChild = oldKeyedChildren[key];if (oldChild != null) {if (Widget.canUpdate(oldChild.widget, newWidget)) {oldKeyedChildren.remove(key);} else {oldChild = null;}}}}// 本例中这里的oldChild.widget与newWidget hashCode相同,在updateChild中成功被复用。// ''' 此处的复用,解决了上面【只是交换了“身体”,而“灵魂”没有交换】的问题 '''final Element newChild = updateChild(oldChild, newWidget, previousChild);newChildren[newChildrenTop] = newChild;previousChild = newChild;newChildrenTop += 1;}// 重置newChildrenBottom = newWidgets.length - 1;oldChildrenBottom = oldChildren.length - 1;// 将后面相同的Element更新后添加到newChildren,至此形成新的完整的children。while ((oldChildrenTop <= oldChildrenBottom) &&(newChildrenTop <= newChildrenBottom)) {final Element oldChild = oldChildren[oldChildrenTop];final Widget newWidget = newWidgets[newChildrenTop];final Element newChild = updateChild(oldChild, newWidget, previousChild);newChildren[newChildrenTop] = newChild;previousChild = newChild;newChildrenTop += 1;oldChildrenTop += 1;}// 清除旧列表中多余的Elementif (haveOldChildren && oldKeyedChildren.isNotEmpty) {for (Element oldChild in oldKeyedChildren.values) {if (forgottenChildren == null || !forgottenChildren.contains(oldChild))deactivateChild(oldChild);}}return newChildren;}
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
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
