Widget是什么?
Widget是描述UI元素Element的配置數(shù)據(jù);一個Widget可以對應(yīng)多個Element,即:同一份配置,可生成多個Element;每個Element都會對應(yīng)一個Widget。
abstract class Widget extends DiagnosticableTree {
const Widget({ this.key });
final Key key;
@protected
Element createElement();
...
static bool canUpdate(Widget oldWidget, Widget newWidget) {
return oldWidget.runtimeType == newWidget.runtimeType
&& oldWidget.key == newWidget.key;
}
}
Key
控制一個widget如何替換樹中另一個widget。如果兩個widget的runtimeType與key相同,則表示新的widget將替換舊的widget,并調(diào)用Element.update更新Element;否則舊的element將從樹中移出,新的element插入樹中。
另外,使用GlobalKey作為widget的key時,允許element在樹上移動(changing parent)不會丟失狀態(tài)。當(dāng)找到新的widget的runtimeType與key與之前相同位置的widget不一致,但是在前一幀樹中的其他位置有個與舊widget具有相同globalKey的widget,然后將該widget的element移動到新的位置。
createElement
給定的widget可以被包含在樹中零次或多次。特別是給定的widget可以被放置到樹中多次。每次一個widget被放置到樹中時,都會注入到一個element中,這意味著widget合并到樹中多次也會被多次注入。
canUpdate
新舊兩個widget的 runtimeType與key是否相同, 決定一個使用oldWidget作為自己配置的element,是否能夠使用newWidget更新它自己。如果兩個widget沒有key,則認(rèn)為它們是匹配的,即使children 完全不相同。
具體的關(guān)于canUpdate的處理邏輯,如下圖。

Flutter中的Element(下篇)
Flutter中的Element(上篇)
iOS 解決 [NSURL fileURLWithPath:] 對 # 的編碼問題
Xcode 調(diào)整導(dǎo)航目錄字體大小b
Swift 5.1 (21) - 泛型
Swift 5.1 (20) - 協(xié)議
Swift 5.1 (19) - 擴展
Swift 5.1 (18) - 嵌套類型
Swift 5.1 (17) - 類型轉(zhuǎn)換與模式匹配
淺談編譯過程