一. 使用
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
, 其内部保存的是Element
树中的所有InheritedElement
.
// Element
Map<Type, InheritedElement>? _inheritedWidgets;
当Element
插入树中的时候(mount()
和activate()
), 会调用_updateInheritance()
, 当前Element
会引用父节点的_inheritedWidgets
.
// Element
void _updateInheritance() {
assert(_lifecycleState == _ElementLifecycle.active);
_inheritedWidgets = _parent?._inheritedWidgets;
}
如果当前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
的使用时机
在上面的例子里, Child
是通过ShareDataWidget.of(context)
获取ShareDataWidget
的.
static ShareDataWidget? of(BuildContext context) {
return context.dependOnInheritedWidgetOfExactType<ShareDataWidget>
();
}
可以看到例子中是通过dependOnInheritedWidgetOfExactType()
得到的ShareDataWidget
. 除了dependOnInheritedWidgetOfExactType()
可以获得对应的InheritedWidget
, 也可以使用getElementForInheritedWidgetOfExactType()
获取对应的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
获取到对应的Element
. 两者的区别除了前者拿到了Element
之后返回的是Element.widget
, 前者首先调用了_dependencies ??= HashSet<InheritedElement>()
, 这是将InheritedElement
保存到了当前Element
的_dependencies
中.
后续调用了updateDependencies()
, 这个函数最终将当前Element
保存到了InheritedElement
的_dependents
内.
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
的使用
当InheritedWidget
改变时, 对应的InheritedElement
会调用update()
, 在后续调用过程中, 调取updateShouldNotify()
判断是否继续调用, 并最终调用到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
进行验证, 将满足互相存有条件的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();
}
最终调用到dependent.didChangeDependencies
.
如果dependent
是StatefulElement
, 则会修改_didChangeDependencies = true
, 当前StatefulElement
调用performRebuild()
的时候, 如果_didChangeDependencies == true
, 就会调用state.didChangeDependencies()
.
如果dependent
不是StatefulElement
, 就会将dependent
标记为dirty
, 在下一帧的时候rebuild
.
总结:
-
InheritWidget
是通过Element._inheritedWidgets
层层传递保存, 相当于是一个全局变量, 在需要的时候读取即可. - 某个
Element
通过dependOnInheritedWidgetOfExactType()
的方式获取InheritWidget
会将这个Element
保存在获取到的InheritedElement
的_dependents
中, 那么当InheritWidget
改变后触发InheritedElement.update()
, 进而在后续过程中读取_dependents
拿到依赖这个InheritedElement
的Element
. - 如果
StatefulElement
依赖了一个InheritedElement
, 当InheritedElement
的InhteritedWidget
发生改变且updateShouldNotify() == true
时,将StatefulElement
标记为dirty
, 将_didChangeDependencies
改为true
, 在下一帧rebuild
被标记为dirty
的Element
时, 通过performRebuild()
最终触发State.didChangeDependencies()
.