[英]Flutter: Access data from InheritedWidgets without context?
I see that I can access InheritedWidgets inside the build()
method like this: final inheritedWidget = ChronoApp.of(context);
我看到我可以在
build()
方法中访问InheritedWidgets,如下所示: final inheritedWidget = ChronoApp.of(context);
but what if I want to access it somewhere else, say in initState()
which has no context. 但是如果我想在其他地方访问它,比如在
initState()
中没有上下文。 How would I do this? 我该怎么做?
According to this docs context
should be available in initState
using the context
getter. 根据此文档,
context
应该在initState
使用context
getter。
https://docs.flutter.io/flutter/widgets/State/context.html https://docs.flutter.io/flutter/widgets/State/context.html
The framework associates State objects with a BuildContext after creating them with StatefulWidget.createState and before calling initState.
在使用StatefulWidget.createState创建它们之前和调用initState之前,框架将State对象与BuildContext相关联。
What I found to work for me is getting the parent context and using it in the didChangeDependencies()
function that is called after initState. 我发现为我工作的是获取父上下文并在initState之后调用的
didChangeDependencies()
函数中使用它。 Like this 像这样
@override
// TODO: implement context
BuildContext get context => super.context;
@override
void didChangeDependencies() {
bloc = LoginBlocProvider.of(context);
bloc.isAuthenticated.listen((bool value) {
setState(() {
isLoading = false;
});
if (value) {
Navigator.push(context, MaterialPageRoute(
builder: (BuildContext context) => HomeScreen()
));
}
});
super.didChangeDependencies();
}
From de didChangeDependencies() docs: 来自de didChangeDependencies()docs:
This method is also called immediately after initState.
在initState之后也会立即调用此方法。 It is safe to call BuildContext.inheritFromWidgetOfExactType from this method.
从此方法调用BuildContext.inheritFromWidgetOfExactType是安全的。
I'm still trying to fully understand this feature but this is what worked for me 我仍然试图完全理解这个功能,但这对我有用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.