Key
StatefulWidget
在Android Studio中经常会使用stful这样一个快捷输入方式来创建一个Widget,其默认实现如下:
class KeyDemo extends StatefulWidget {const KeyDemo({Key? key}) : super(key: key);@override_KeyDemoState createState() => _KeyDemoState();}class _KeyDemoState extends State<KeyDemo> {@overrideWidget build(BuildContext context) {return Container();}}
我们在之前的使用这样的Widget的时候,没有去关心过const KeyDemo({Key? key}) : super(key: key);这行代码究竟有何意义,有时候我们甚至直接将其删除,也没有引起任何开发或者布局问题;那么这行代码究竟有什么用处呢?
我们可以看到,它其实是一个构造函数,默认传递了一个Key的参数,从源码中我们也可以看到所有的Widget都有这个Key:
Key为空安全的,可用可不用;
我们将代码修改如下:
在KeyDemo中添加三个随机颜色的WidgetItem,点击悬浮按钮是,删除三个WidgetItem中的第一个,我们可以查看一下,运行效果:
我们这个时候发现结果跟我们的预期并不一样:删除之后的颜色块和文字没有对上;
文字每一次删除的是第一个,而颜色块每次删除的确实最后一个
StatelessWidget
接下来,我们将上述代码中WidgetItem从StatefulWidget修改为StatelessWidget,然后在运行看一下结果:
我们发现此时,运行效果与我们预期相一致,每次都删除第一个WidgetItem;
那么,为什么当我们使用StatefulWidget的时候结果会有偏差,而使用StatelessWidget结果就正常了呢?那么是不是我们就不能使用StatefulWidget来实现这样的效果了呢?
当然不是,我们依然可以使用StatefulWidget来实现一模一样的效果,这个时候我们就需要使用Widget的Key属性了,我们使用继承自StatefulWidget的WidgetItem,并将其构造方法传值修改如下:
在WidgetItem的构造函数中给key属性赋值(key属性值不能重复),结果就和我们预期结果一直;
我们会有疑惑,为什么加了key结果就发生了改变呢?我们注意到,此种情况发生在StatefulWidget上,而StatelessWidget却没有,那么StatefulWidget和StatelessWidget究竟有什么不一样呢?
接下来我们比较一下,继承自StatefulWidget的WidgetItem和继承自StatelessWidget的WidgetItem有何区别?
继承自
StatefulWidget的WidgetItem: ```dart class WidgetItem extends StatefulWidget { final String title; const WidgetItem(this.title, {Key? key}) : super(key: key);@override _WidgetItemState createState() => _WidgetItemState(); }
class _WidgetItemState extends State
final randomColor = Color.fromRGBO( Random().nextInt(256), Random().nextInt(256), Random().nextInt(256), 1 );
@override Widget build(BuildContext context) { return Container( width: 100, height: 100, color: randomColor, child: Text(widget.title), ); } }
- 继承自`StatelessWidget`的`WidgetItem`:```dartclass WidgetItem extends StatelessWidget {final String title;WidgetItem(this.title, {Key? key}) : super(key: key);final randomColor = Color.fromRGBO(Random().nextInt(256),Random().nextInt(256),Random().nextInt(256),1);@overrideWidget build(BuildContext context) {return Container(width: 100,height: 100,color: randomColor,child: Text(title),);}}
我们发现两个WidgetItem中randomColor的所属不同,在StatelessWidget中randomColor属于当前Widget,而在StatefulWidget中randomColor属于当前Widget的State,那么是不是把randomColor从State中放进Widget中就可以了呢?
我们修改代码如下,查看运行结果:
此时我们发现,将randomColor的位置改变之后,即使我们不使用key属性,也达到了同样的效果;
那么究竟是什么原因倒是这样的情况呢?从我们错误的效果中,可以分析到这样的情况:
["第一个","第二个","第三个"]这数组中的第一个元素确实被删除了,然后剩余两个元素- 三个颜色块并没有被删除,因为只剩下两个元素,所以最后一个颜色块没有显示出来
Widget被删除了,而State没有被删除;
我们来验证一下,我们将randomColor重新放回State中,然后在删除第一个元素的时候,再添加第四个元素(不使用Key属性),我们看如下代码及结果:
结果和我们预测的一模一样,数组元素也就是Widget被删除了,但是颜色块依然存在,并没有被删除;
此时,我们也可以通过
Debbug模式断点,可以确定StatefulWidget的createElement()方法并没有执行,也就是我们再删除一个Widget之后,立刻添加一个新的Widget,但是Element并没有重新创建;
这是什么原因引起的呢?我们从Widget的源码中可以看到这样一个方法的实现:
/// 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;}
该方法有什么作用呢?我们之前已经讲过Flutter之所以渲染效率高,是因为Flutter采用的是增量渲染的机制,那么如何判断一个Widget应该被更新重新渲染呢?就是用过此方法进行判断;
从Debug的结果和注释中我们可以看到,oldWidget和newWidget的runtimeType是一直的,而前后两个Widget的key属性都为null,所以他们匹配成功,可以使用newWidget来更新oldWidget的Element;
流程分析
其大致流程如下:
- 第一步:我们的页面运行起来的时候,当
Widget树被创建(下图左侧),同时Element树也会被创建(下图右侧):

- 第二步:删除第一个
Widget之后,在判断是否需要更新时canUpdate,因为第一个Widget已经不存在,那么就是使用第一个Element去判断第二个Widget是否可更新,同样的,拿第二个Element去判断第三个Widget是否可更新,因为Widget的runtimeType一直并且key为空,所以将会返回true,允许更新:

因为我们的颜色
randomColor是保存在了State中,而State是保存在Element中的(StatefulElement的构造方法中会调用widget.createState方法);所以导致文字改变了,而颜色没有改变的情况出现;
