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 天前
4:2:1!老刘的三季度项目报告
flutter·harmonyos·客户端
达达尼昂1 天前
🎯 Flutter 拖拽选择组件:flutter_drag_selector —— 像选文件一样选择列表项
前端·flutter
QuantumLeap丶1 天前
《Flutter全栈开发实战指南:从零到高级》- 15 -本地数据存储
flutter·ios·dart
法的空间1 天前
让 Flutter 资源管理更智能
android·flutter·ios
江上清风山间明月1 天前
Flutter中Column中使用ListView时溢出问题的解决方法
android·flutter·column·listview
恋猫de小郭1 天前
Snapchat 开源全新跨平台框架 Valdi ,一起来搞懂它究竟有什么特别之处
android·前端·flutter
西西学代码1 天前
Flutter---函数
flutter
西西学代码1 天前
Flutter---Stream
java·服务器·flutter
GISer_Jing2 天前
2025年Flutter与React Native对比
android·flutter·react native