我们都知道StatefulWidget可以进行页面刷新操作,而StatelessWidget并不具备这项功能,依旧在最开始抛出两个问题:
abstract class State<T extends StatefulWidget>...{
void setState(VoidCallback fn) {
...
final dynamic result = fn() as dynamic;
_element.markNeedsBuild();
}
}
//在Element类中
{
void markNeedsBuild() {
...
if (dirty) //如果是已经标记为脏,则直接结束
return;
_dirty = true;
owner.scheduleBuildFor(this);
}
}
//owner属于BuildOwner类
class BuildOwner {
void scheduleBuildFor(Element element) {
...
_dirtyElements.add(element);
}
void buildScope(Element context, [ VoidCallback callback ]) {
...
while (index < dirtyCount) {
_dirtyElements[index].rebuild();
}
}
}
//而rebuild最终还是会回到我们熟悉的performRebuild方法里,除了最基本的build方法。
void performRebuild() {
...
built = build();
...
_child = updateChild(_child, built, slot);
}
目前还有一个问题buildScope这个方法是否是Flutter隐式调用的呢?有答案的同学可以指教指教。目前没找到调用的位置。
updateChild
这个方法里,目前为止当前包含当前Widget的Element就会进入到updateChild更新流程里。_dirty
这个参数的使用,我认为是非常优化的。即使你做出重复刷新的操作也不会导致页面的重复刷新。StatelessElement
中并没有找到setState等刷新方法,所以无法支持刷新,回答了之前的问题一。虽然依旧可以以类似的方式实现为StatefulWidget的子类,但是会有问题,这里就不具体说明,可以参考Flutter文档Why is the build method on State, and not StatefulWidget? // 只有类型相同且key相同的就是可以刷新的
static bool canUpdate(Widget oldWidget, Widget newWidget) {
return oldWidget.runtimeType == newWidget.runtimeType
&& oldWidget.key == newWidget.key;
}
Element updateChild(Element child, Widget newWidget, dynamic newSlot) {
//如果在widgetTree中当前widget被删除则直接结束,并在ElementTree中也删除它
if (newWidget == null) {
deactivateChild(child);
return;
}
...
Element newChild;
if (child != null) {
...
if (hasSameSuperclass && child.widget == newWidget) {
//如果相同则不进行updata操作
newChild = child;
} else if (hasSameSuperclass && Widget.canUpdate(child.widget, newWidget)) {
//如果可以更新则进行update操作
child.update(newWidget);
newChild = child;
}else{
//inflateWidget中会执行createElement这里就不多赘述了
newChild = inflateWidget(newWidget, newSlot);
}
}
}
void update(covariant Widget newWidget) {
...
_widget = newWidget;
}
Element inflateWidget(Widget newWidget, dynamic newSlot) {
...
final Element newChild = newWidget.createElement();
newChild.mount(this, newSlot);
}
oldWidget.key == newWidget.key
默认为true。如果不想要进行复用的Widget则使用不同的key就可以实现。update
要注意方法中的_widget = newWidget
,更新后会持有newWidget。inflateWidget
在遇到需要创建新的Element的时候,看到了上一篇遇到过的createElement
,mount
也佐证了之前的Widget创建到Element的创建过程。