didChangeDependencies和initState之间的区别是什么? [英] What is diffrence between didChangeDependencies and initState?

查看:197
本文介绍了didChangeDependencies和initState之间的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是扑朔迷离的新手,当我想在InitState中调用上下文时,会引发错误:
,大约等于
BuildContext.inheritFromWidgetOfExactType
,但随后我使用didChangeDependencies正常运行。

I am new to flutter and when I want to call my context in InitState it throw an error : which is about BuildContext.inheritFromWidgetOfExactType but then I use didChangeDependencies and it work correctly.

现在我有2个问题:

1-为什么我们不能在initState中调用上下文,但是didChangeDependencies没有问题?
(因为我在官方文档中读过,所以此方法在[initState] 之后也立即调用,
两者都将在build方法之前被调用。

1-why we can't call our context in initState but there is no problem for didChangeDependencies ? (because as I read in official doc This method is also called immediately after [initState], and both of them will be called before build method. )

2-为什么我们可以在build方法之外访问上下文(因为那里有 build(BuildContext context)并且我们可以使用上下文,但是在didChangeDependencies中,我们没有像 didChangeDependencies(BuildContext context)这样的东西,因此我们可以从哪里调用上下文来使用它?) p>

2-why we have access to context outside build method ( because there we have build(BuildContext context) and we can use our context but in didChangeDependencies we don't have anything like didChangeDependencies(BuildContext context) , so from where we can call context to use it) ?

推荐答案


从状态加载其依赖项之时起,我们就可以使用状态上下文。

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

在调用构建时,上下文可供我们使用并作为参数传递。

At the time build is called, context is available to us and is passed as an argument.

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

Now moving on, initstate is called before the state loads its dependencies and for that reason no context is available and you get an error for that if u use context in initstate. However didChangeDependencies is called just few moments after the state loads its dependencies and context is available at this moment so here you can use context.


但是在调用build之前都调用了它们。
唯一的区别是,一个在状态加载其依赖项之前调用,而另一个在状态加载其依赖项之后调用。

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.

这篇关于didChangeDependencies和initState之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆