Flutter: Access data from InheritedWidgets without context?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP

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); but what if I want to access it somewhere else, say in initState() which has no context. How would I do this?


build()


final inheritedWidget = ChronoApp.of(context);


initState()




2 Answers
2



According to this docs context should be available in initState using the context getter.


context


initState


context



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.





Yes, that's what I meant. I think I used this myself somewhere, but I'm not sure.
– Günter Zöchbauer
Apr 22 at 16:40



What I found to work for me is getting the parent context and using it in the didChangeDependencies() function that is called after initState. Like this


didChangeDependencies()


@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:



This method is also called immediately after initState. It is safe to
call BuildContext.inheritFromWidgetOfExactType from this method.



I'm still trying to fully understand this feature but this is what worked for me






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

Executable numpy error

Trying to Print Gridster Items to PDF without overlapping contents

Mass disable jenkins jobs