flutter 为什么大家说不能在initState 方法中调用dependOnInheritedWidgetOfExactType

138 阅读1分钟
/// This method should not be called from widget constructors or from
/// [State.initState] methods, because those methods would not get called
/// again if the inherited value were to change. To ensure that the widget
/// correctly updates itself when the inherited value changes, only call this
/// (directly or indirectly) from build methods, layout and paint callbacks,
/// or from [State.didChangeDependencies] (which is called immediately after
/// [State.initState]).

这个是dependOnInheritedWidgetOfExactType注释的一部分,主要说的就是为什么不让在initState中调用,并不是说不可以调用。只是说initState方法只会调用一次,后续数据发生改变的时候,initState不会再次调用,不能及时刷新。所以建议我们在didChangeDependencies中调用,数据发生变化的时候didChangeDependencies肯定会回调。并且第一次initState之后也会调用一次didChangeDependencies方法。

这样就可以保证第一次或者后续数据发生变化的时候都可以获取到最新的数据。

Elementmount方法中会调用_firstBuild StatefulElement_firstBuild的实现如下。

@override
void _firstBuild() {
  assert(state._debugLifecycleState == _StateLifecycle.created);
  final Object? debugCheckForReturnedFuture = state.initState() as dynamic;
  。。。。
  state.didChangeDependencies();
  assert(() {
    state._debugLifecycleState = _StateLifecycle.ready;
    return true;
  }());
  super._firstBuild();
}