[Flutter] 04、Widget

64 阅读1分钟

Flutter 作为跨平台的U库,区别于原生技术。描述视图的Widget和View到底有啥区别。Widget到底是什么。

1、一切皆为Widget

Flutter 设计的核心思想:一切皆为Wdiget.

1.1 Widget的渲染过程

@immutable
abstract class Widget extends DiagnosticableTree {
  ...
  /// Inflates this configuration to a concrete instance.
  ///
  /// A given widget can be included in the tree zero or more times. In particular
  /// a given widget can be placed in the tree multiple times. Each time a widget
  /// is placed in the tree, it is inflated into an [Element], which means a
  /// widget that is incorporated into the tree multiple times will be inflated
  /// multiple times.
  @protected
  @factory
  Element createElement();
  ...
}

1.1.1 关于Element

abstract class Element extends DiagnosticableTree implements BuildContext {

  @nonVirtual
  @override
  // ignore: avoid_equals_and_hash_code_on_mutable_classes, hash_and_equals
  bool operator ==(Object other) => identical(this, other);
  
  
}

1.1.2 diff

从底层Widget的代码,不难看出,Widget的数据结构是一个DiagnosticableTree, 创建Widget的过程中,调用了createElement, 从Element的代码过程中,我们也不难看出。Widget的创建过程中会创建一个与之对应的Element树,那Element树就是负责渲染的吗?

1.1.3 关于Element树的作用

  • Element 树会对child节点去排序,遍历。找到需要更新的节点,并将节点标记为dirty

log

2023.03.28 1.1.3