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();
}
相关推荐
恋猫de小郭12 小时前
Android 17 + OkHttp 5.5.0 ,全新 ECH 下你的 HTTPS 域名可以请求时被安全隐藏
android·前端·flutter
「、皓子~2 天前
海狸IM 2.1 正式发布
flutter·微服务·golang·electron·开源软件·im·海狸im
里欧跑得慢2 天前
AI 驱动的 UI 国际化方案自动适配:从单一语言到多语言布局的智能转换
前端·css·flutter·web
恋猫de小郭2 天前
AI 时代,一个优化 Flutter 的重复代码工具 Deslop
android·前端·flutter
ljt27249606613 天前
Flutter笔记--envied
前端·笔记·flutter
加农炮手Jinx3 天前
Flutter for OpenHarmony 实战:flutter_animate 声明式动画让 UI 灵动如原生
flutter·ui·华为·harmonyos·鸿蒙
里欧跑得慢3 天前
Flutter 像素级还原:设计稿到代码的视觉无损转换技巧
前端·css·flutter·web
里欧跑得慢3 天前
Flutter 三方库 function_tree — 鸿蒙应用开发中的动态数学公式解析与计算神器,实现鸿蒙深度适配下的复杂函数逻辑运行时求值实战(适配鸿蒙 HarmonyOS Next ohos)
android·前端·安全·flutter·华为·harmonyos
吃西瓜的年年4 天前
vue3原理思维导图
vue.js·笔记·flutter