flutter widget element api粗略结构图

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;
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容