一. 使用
class Parent extends StatefulWidget {
const Parent({Key? key}) : super(key: key);
}
class _ParentState extends State<Parent> {
bool inContainer = false;
final GlobalKey _gk = GlobalKey();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('one child'),
),
body: Column(
children: [
ElevatedButton(
onPressed: () {
setState(() {
inContainer = !inContainer;
});
},
child: const Text('change'),
),
// `MiddleWidget`表示一層或多層`Widget`
ShareDataWidget(
inContainer ? 1 : 2,
child: const MiddleWidget(
child: Child(),
),
)
],
),
);
}
}
class ShareDataWidget extends InheritedWidget {
final int data;
const ShareDataWidget(
this.data, {
Key? key,
required Widget child,
}) : super(key: key, child: child);
static ShareDataWidget? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<ShareDataWidget>();
}
@override
bool updateShouldNotify(covariant ShareDataWidget oldWidget) {
return oldWidget.data != data;
}
}
class Child extends StatefulWidget {
const Child({Key? key}) : super(key: key);
@override
State<Child> createState() {
return _ChildState();
}
}
class _ChildState extends State<Child> {
@override
Widget build(BuildContext context) {
return Text('data: {ShareDataWidget.of(context)?.data ?? -1}');
}
}
二. 原理
1. Element
的成員變量 _inheritedWidgets
Element
有一個成員變量_inheritedWidgets
, 其內(nèi)部保存的是Element
樹中的所有InheritedElement
.
// Element
Map<Type, InheritedElement>? _inheritedWidgets;
當(dāng)Element
插入樹中的時候(mount()
和activate()
), 會調(diào)用_updateInheritance()
, 當(dāng)前Element
會引用父節(jié)點(diǎn)的_inheritedWidgets
.
// Element
void _updateInheritance() {
assert(_lifecycleState == _ElementLifecycle.active);
_inheritedWidgets = _parent?._inheritedWidgets;
}
如果當(dāng)前Element
是InheritedElement
, 會將自己添加到_inheritedWidgets
.
@override
void _updateInheritance() {
assert(_lifecycleState == _ElementLifecycle.active);
final Map<Type, InheritedElement>? incomingWidgets = _parent?._inheritedWidgets;
if (incomingWidgets != null)
_inheritedWidgets = HashMap<Type, InheritedElement>.of(incomingWidgets);
else
_inheritedWidgets = HashMap<Type, InheritedElement>();
_inheritedWidgets![widget.runtimeType] = this;
}
2. _inheritedWidgets
的使用時機(jī)
在上面的例子里, Child
是通過ShareDataWidget.of(context)
獲取ShareDataWidget
的.
static ShareDataWidget? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<ShareDataWidget>
();
}
可以看到例子中是通過dependOnInheritedWidgetOfExactType()
得到的ShareDataWidget
. 除了dependOnInheritedWidgetOfExactType()
可以獲得對應(yīng)的InheritedWidget
, 也可以使用getElementForInheritedWidgetOfExactType()
獲取對應(yīng)的InheritedElement
.
@override
InheritedWidget dependOnInheritedElement(InheritedElement ancestor, { Object? aspect }) {
assert(ancestor != null);
_dependencies ??= HashSet<InheritedElement>();
_dependencies!.add(ancestor);
ancestor.updateDependencies(this, aspect);
return ancestor.widget as InheritedWidget;
}
@override
T? dependOnInheritedWidgetOfExactType<T extends InheritedWidget>({Object? aspect}) {
assert(_debugCheckStateIsActiveForAncestorLookup());
final InheritedElement? ancestor = _inheritedWidgets == null ? null : _inheritedWidgets![T];
if (ancestor != null) {
return dependOnInheritedElement(ancestor, aspect: aspect) as T;
}
_hadUnsatisfiedDependencies = true;
return null;
}
@override
InheritedElement? getElementForInheritedWidgetOfExactType<T extends InheritedWidget>() {
assert(_debugCheckStateIsActiveForAncestorLookup());
final InheritedElement? ancestor = _inheritedWidgets == null ? null : _inheritedWidgets![T];
return ancestor;
}
3.Element._dependencies
和InheritedElement._dependents
dependOnInheritedWidgetOfExactType()
和getElementForInheritedWidgetOfExactType()
都是讀取_inheritedWidgets
獲取到對應(yīng)的Element
. 兩者的區(qū)別除了前者拿到了Element
之后返回的是Element.widget
, 前者首先調(diào)用了_dependencies ??= HashSet<InheritedElement>()
, 這是將InheritedElement
保存到了當(dāng)前Element
的_dependencies
中.
后續(xù)調(diào)用了updateDependencies()
, 這個函數(shù)最終將當(dāng)前Element
保存到了InheritedElement
的_dependents
內(nèi).
Element._dependencies
和InheritedElement._dependents
互相保存彼此.
// InheritedElement
final Map<Element, Object?> _dependents = HashMap<Element, Object?>();
@protected
void updateDependencies(Element dependent, Object? aspect) {
setDependencies(dependent, null);
}
@protected
void setDependencies(Element dependent, Object? value) {
_dependents[dependent] = value;
}
4. Element._dependencies
和InheritedElement._dependents
的使用
當(dāng)InheritedWidget
改變時, 對應(yīng)的InheritedElement
會調(diào)用update()
, 在后續(xù)調(diào)用過程中, 調(diào)取updateShouldNotify()
判斷是否繼續(xù)調(diào)用, 并最終調(diào)用到notifyClients()
.
// ProxyElement, InheritedElement繼承自ProxyElement
@override
void update(ProxyWidget newWidget) {
final ProxyWidget oldWidget = widget as ProxyWidget;
assert(widget != null);
assert(widget != newWidget);
super.update(newWidget);
assert(widget == newWidget);
updated(oldWidget);
_dirty = true;
rebuild();
}
// InheritedElement
@override
void updated(InheritedWidget oldWidget) {
if ((widget as InheritedWidget).updateShouldNotify(oldWidget))
super.updated(oldWidget);
}
@override
void notifyClients(InheritedWidget oldWidget) {
assert(_debugCheckOwnerBuildTargetExists('notifyClients'));
for (final Element dependent in _dependents.keys) {
assert(() {
// check that it really is our descendant
Element? ancestor = dependent._parent;
while (ancestor != this && ancestor != null)
ancestor = ancestor._parent;
return ancestor == this;
}());
// check that it really depends on us
assert(dependent._dependencies!.contains(this));
notifyDependent(oldWidget, dependent);
}
}
在notifyClients()
中, 通過InheritedElement._dependents
和Element._dependencies
進(jìn)行驗(yàn)證, 將滿足互相存有條件的Element
傳入notifyDependent()
// InheritedElement
@protected
void notifyDependent(covariant InheritedWidget oldWidget, Element dependent) {
dependent.didChangeDependencies();
}
// Element
@mustCallSuper
void didChangeDependencies() {
assert(_lifecycleState == _ElementLifecycle.active); // otherwise markNeedsBuild is a no-op
assert(_debugCheckOwnerBuildTargetExists('didChangeDependencies'));
markNeedsBuild();
}
// StatefulElement
@override
void didChangeDependencies() {
super.didChangeDependencies();
_didChangeDependencies = true;
}
@override
void performRebuild() {
if (_didChangeDependencies) {
state.didChangeDependencies();
_didChangeDependencies = false;
}
super.performRebuild();
}
最終調(diào)用到dependent.didChangeDependencies
.
如果dependent
是StatefulElement
, 則會修改_didChangeDependencies = true
, 當(dāng)前StatefulElement
調(diào)用performRebuild()
的時候, 如果_didChangeDependencies == true
, 就會調(diào)用state.didChangeDependencies()
.
如果dependent
不是StatefulElement
, 就會將dependent
標(biāo)記為dirty
, 在下一幀的時候rebuild
.
總結(jié):
-
InheritWidget
是通過Element._inheritedWidgets
層層傳遞保存, 相當(dāng)于是一個全局變量, 在需要的時候讀取即可. - 某個
Element
通過dependOnInheritedWidgetOfExactType()
的方式獲取InheritWidget
會將這個Element
保存在獲取到的InheritedElement
的_dependents
中, 那么當(dāng)InheritWidget
改變后觸發(fā)InheritedElement.update()
, 進(jìn)而在后續(xù)過程中讀取_dependents
拿到依賴這個InheritedElement
的Element
. - 如果
StatefulElement
依賴了一個InheritedElement
, 當(dāng)InheritedElement
的InhteritedWidget
發(fā)生改變且updateShouldNotify() == true
時,將StatefulElement
標(biāo)記為dirty
, 將_didChangeDependencies
改為true
, 在下一幀rebuild
被標(biāo)記為dirty
的Element
時, 通過performRebuild()
最終觸發(fā)State.didChangeDependencies()
.