flutter - didChangeDependencies 和 initState 有什么区别?

标签 flutter dart

我是 flutter 新手,当我想在 InitState 中调用我的上下文时,它会抛出一个错误:
这是关于BuildContext.inheritFromWidgetOfExactType但是后来我使用了 didChangeDependencies 并且它工作正常。
现在我有两个问题:
1- 为什么在 initState 中调用我们的上下文不起作用,但在从 didChangeDependencies 调用时却起作用?
(因为我在官方文档 This method is also called immediately after [initState] 中读到,
并且它们都将在 build 方法之前被调用。 )
2- 为什么我们可以在 build 方法之外访问我们的上下文(因为我们有 build(BuildContext context) 并且我们可以使用我们的上下文,但是在 didChangeDependencies 中我们没有像 didChangeDependencies(BuildContext context) 这样的东西,所以我们可以从哪里调用 context 到用它) ?

最佳答案

Context of a state is available to us from the moment the State loads its dependencies.



在调用 build 时,上下文对我们可用并作为参数传递。

现在继续前进,
initstate 在状态加载其依赖项之前被调用,因此没有可用的上下文,如果您在 initstate 中使用上下文,则会出现错误。
但是 didChangeDependencies 在状态加载其依赖项后不久被调用,此时上下文可用,因此您可以在此处使用上下文。

However both of them are called before build is called. Only difference is that one is called before the state loads its dependencies and other is called a few moments after the state loads its dependencies.

关于flutter - didChangeDependencies 和 initState 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58371874/

相关文章:

flutter 验证单选按钮

android - 如何从 Flutter 的通知栏中删除所有通知?

flutter - 如何在Flutter中使用自定义小部件

dart - 如何避免为 dart/flutter 中的每个文件编写导入?

android - CrossAxisAlignment.center 从不在 Column 中工作

java - Flutter/Java Plot Mp3 频率强度

xcode - Flutter FCM Ios 未在设备上显示

Flutter - 如何检查 SingleChildScrollView 是否适合屏幕

testing - 如何在小部件测试中等待 Future 方法?

dart - 如何知道用户是否看到了 flutter 图像