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与OpenHarmony ArkUI组件互通的Electron桌面应用UI优化方案
flutter·ui·electron
吃好喝好玩好睡好1 天前
OpenHarmony混合开发实战指南
c语言·python·flutter·vr·visual studio
松☆1 天前
OpenHarmony + Flutter 混合开发高阶:实现无障碍(Accessibility)与适老化 UI 的深度集成
flutter·ui
Non-existent9871 天前
Flutter + FastAPI 30天速成计划自用并实践-第6天
flutter·fastapi
克喵的水银蛇1 天前
Flutter 通用弹窗组件:CommonDialog 一键实现自定义弹窗
flutter
解局易否结局1 天前
Flutter:重塑跨平台开发的生态与实践
flutter
Android_Trot1 天前
Flutter android 多渠道配置,多包名、icon、等配置。
android·flutter
淡写成灰1 天前
Flutter PopScope 返回拦截完整指南
flutter
ujainu1 天前
Flutter与DevEco Studio协同开发:HarmonyOS应用实战指南
flutter·华为·harmonyos