美文网首页
InheritedWidget 原理

InheritedWidget 原理

作者: 烟影很美 | 来源:发表于2022-08-19 20:25 被阅读0次

一. 使用

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;
}

如果当前ElementInheritedElement, 会将自己添加到_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._dependenciesInheritedElement._dependents

dependOnInheritedWidgetOfExactType()getElementForInheritedWidgetOfExactType()都是读取_inheritedWidgets获取到对应的Element. 两者的区别除了前者拿到了Element之后返回的是Element.widget, 前者首先调用了_dependencies ??= HashSet<InheritedElement>(), 这是将InheritedElement保存到了当前Element_dependencies中.

后续调用了updateDependencies(), 这个函数最终将当前Element保存到了InheritedElement_dependents内.

Element._dependenciesInheritedElement._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._dependenciesInheritedElement._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._dependentsElement._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.

如果dependentStatefulElement, 则会修改_didChangeDependencies = true, 当前StatefulElement调用performRebuild()的时候, 如果_didChangeDependencies == true, 就会调用state.didChangeDependencies().

如果dependent不是StatefulElement, 就会将dependent标记为dirty, 在下一帧的时候rebuild.

总结:

  1. InheritWidget是通过Element._inheritedWidgets层层传递保存, 相当于是一个全局变量, 在需要的时候读取即可.
  2. 某个Element通过dependOnInheritedWidgetOfExactType()的方式获取InheritWidget会将这个Element保存在获取到的InheritedElement_dependents中, 那么当InheritWidget改变后触发InheritedElement.update(), 进而在后续过程中读取_dependents拿到依赖这个InheritedElementElement.
  3. 如果StatefulElement依赖了一个InheritedElement, 当InheritedElementInhteritedWidget发生改变且updateShouldNotify() == true时,将StatefulElement标记为dirty, 将_didChangeDependencies改为true, 在下一帧rebuild被标记为dirtyElement时, 通过performRebuild()最终触发State.didChangeDependencies().

相关文章

网友评论

      本文标题:InheritedWidget 原理

      本文链接:https://www.haomeiwen.com/subject/hjaegrtx.html