今天講的是element,官方是這樣解釋element的
element是樹上的某個位子的widget的實例化,不管唸起來還是理解起來都是非常繞口~~不虧是官方連解釋都這麼博大精深。
但是可以簡單理解成
首先要理解這段話最簡單的方式就是source key
abstract class Widget extends DiagnosticableTree {
...
Element createElement();
...
}
widget中有個createElement的method用來create widget的element
abstract class Element extends DiagnosticableTree implements BuildContext {
/// Creates an element that uses the given widget as its configuration.
///
/// Typically called by an override of [Widget.createElement].
Element(Widget widget)
: assert(widget != null),
_widget = widget;
}
element在constructor時會把widget當參數帶進來並存在_widget的變數
abstract class SingleChildRenderObjectWidget extends RenderObjectWidget {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const SingleChildRenderObjectWidget({ Key? key, this.child }) : super(key: key);
/// The widget below this widget in the tree.
///
/// {@macro flutter.widgets.ProxyWidget.child}
final Widget? child;
@override
SingleChildRenderObjectElement createElement() => SingleChildRenderObjectElement(this);
}
從SingleChildRenderObjectWidget實作createElement中可以看到,widget create了element而且在create element時會把widget自己當作參數帶到element裡面。
看到這裡我們也能明白為什麼官方會描述element是widget的實例化了吧!
接下來就是另一個疑問: 被放在樹上某個位子 是什麼意思?
這個我就放到明日繼續(抱歉其實是想今天介紹der)