widget和element的api调用结构图
![](https://img.haomeiwen.com/i13262046/b8577f6febde83d5.png)
关键的updateChild函数
//移除了部分注释,assert
Element updateChild(Element child, Widget newWidget, dynamic newSlot) {
if (newWidget == null) {
if (child != null)
deactivateChild(child);
return null;
}
Element newChild;
if (child != null) {
bool hasSameSuperclass = true;
if (hasSameSuperclass && child.widget == newWidget) {
if (child.slot != newSlot)
updateSlotForChild(child, newSlot);
newChild = child;
} else if (hasSameSuperclass && Widget.canUpdate(child.widget, newWidget)) {
if (child.slot != newSlot)
updateSlotForChild(child, newSlot);
child.update(newWidget);
newChild = child;
} else {
deactivateChild(child);
newChild = inflateWidget(newWidget, newSlot);
}
} else {
newChild = inflateWidget(newWidget, newSlot);
}
return newChild;
}
/// | | newWidget == null | newWidget != null |
/// | :-----------------: | :--------------------- | :---------------------- |
/// | child == null | Returns null. | Returns new [Element]. |
/// | child != null | Old child is removed, returns null. | Old child updated if possible, returns child or new [Element]. |
主要分3大种情况
- 如果newWidget ==null;返回 空element
- 如果newWidget !=null,element ==null; 创建一个element并返回
- 如果newWidget !=null,element !=null;
- element的widget和newWidget 是 同一个对象,返回对象的element
- element的widget和newWidget 不是 同一个对象,判断widget和newWidget是否 能够更新canUpdate()
2.1 能够更新,element更新widget;
2.2 不能更新,创建一个element并返回;
Widget的 static 方法 canUpdate
static bool canUpdate(Widget oldWidget, Widget newWidget) {
return oldWidget.runtimeType == newWidget.runtimeType
&& oldWidget.key == newWidget.key;
}
网友评论