didChangeDependencies和initState有什么区别? [英] What is the difference between didChangeDependencies and initState?

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

问题描述

我是扑朔迷离的新手,当我想在InitState中调用上下文时,会引发错误: 这是关于 BuildContext.inheritFromWidgetOfExactType 但是然后我使用didChangeDependencies,它可以正常工作.

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

现在我有2个问题:

1-为什么在initState中调用我们的上下文不起作用,但是从didChangeDependencies调用时却起作用? (因为我在官方文档This method is also called immediately after [initState]中读过, 并且它们都将在build方法之前被调用. )

1- Why calling our context in initState does not work but it works when calling from 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)的东西,因此我们可以从哪里访问调用上下文以使用它)?

2- Why do we have access to our context outside of 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 can we call context to use it) ?

推荐答案

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

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

在调用build时,我们可以使用上下文并将其作为参数传递.

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天全站免登陆