美文网首页
flutter widget element api粗略结构图

flutter widget element api粗略结构图

作者: only_run | 来源:发表于2020-09-09 10:14 被阅读0次

widget和element的api调用结构图

image.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;
  1. element的widget和newWidget 是 同一个对象,返回对象的element
  2. 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;
}

相关文章

网友评论

      本文标题:flutter widget element api粗略结构图

      本文链接:https://www.haomeiwen.com/subject/suxeektx.html