Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 570
Jus10 Avatar asked Apr 22 '18 16:04

Jus10


People also ask

How do you pass data between widgets in Flutter?

Steps to Pass Data to Stateful Widget in Flutter To pass data to stateful widget, first of all, create two pages. Now from the first page open the second page and pass the data. Inside the second page, access the variable using the widget. For example widget.

How do you use an inherited widget?

To be able to send data to the next widget in the tree, you would have to use the constructor of each widget to pass data from one widget to another. The InheritedWidget solves the above issue, the widget will be able to hold data and send data down in the widget tree without even using the constructor of each widget.

What is an InheritedWidget?

In flutter, the inherited widget is a base class that allows those classes to extend the information under the tree from it. Inherited widgets are also a kind of state management technique. It works by telling registered build references when a change occurs.


2 Answers

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

like image 140
Sebastian Avatar answered Sep 21 '22 17:09

Sebastian


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.

like image 24
Günter Zöchbauer Avatar answered Sep 18 '22 17:09

Günter Zöchbauer