Flutter: Access data from InheritedWidgets without context?
Asked Answered
Q

2

8

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?

Quianaquibble answered 22/4, 2018 at 16:12 Comment(0)
O
9

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

@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

Oneil answered 29/7, 2018 at 21:16 Comment(0)
J
5

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

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.

Joshua answered 22/4, 2018 at 16:21 Comment(3)
Yes, that's what I meant. I think I used this myself somewhere, but I'm not sure.Longhorn
didChangeDependencies() is the better place as its called after the initState() and you will get the context there.Mennonite
I think you are right. didChangeDependencies can be called more than once though.Longhorn

© 2022 - 2024 — McMap. All rights reserved.