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

arduino 复制代码
/// 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的实现如下。

ini 复制代码
@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();
}
相关推荐
世人万千丶1 天前
Flutter 框架跨平台鸿蒙开发 - 恐惧清单应用
学习·flutter·华为·开源·harmonyos·鸿蒙
Utopia^1 天前
Flutter 框架跨平台鸿蒙开发 - 21天挑战
flutter·华为·harmonyos
一直在想名1 天前
Flutter 框架跨平台鸿蒙开发 - 黑白屏
flutter·华为·kotlin·harmonyos
AI_零食1 天前
Flutter 框架跨平台鸿蒙开发 - 孤独指数应用
学习·flutter·开源·harmonyos
浮芷.1 天前
Flutter 框架跨平台鸿蒙开发 - 儿童技能打卡墙应用
科技·flutter·华为·harmonyos·鸿蒙
Utopia^1 天前
Flutter 框架跨平台鸿蒙开发 - 重力感知
flutter·华为·harmonyos
提子拌饭1331 天前
昼夜节律下的肝脏代谢清除率演算仪:基于鸿蒙Flutter的双路流场与酶解粒子对照架构
flutter·华为·架构·harmonyos·鸿蒙
小雨天気.1 天前
Flutter 框架跨平台鸿蒙开发 - 直觉训练器应用
flutter·华为·harmonyos
浮芷.1 天前
Flutter 框架跨平台鸿蒙开发 - 姿势纠正助手应用
科技·flutter·华为·harmonyos·鸿蒙
一直在想名1 天前
Flutter 框架跨平台鸿蒙开发 - 影子收藏家
flutter·华为·harmonyos