Correct Flutter widget sequence to pull data on app load

Actually you cannot access InheritedWidget from an initState method. Instead try accessing it from didChangeDependencies.

Example:

@override
void didChangeDependencies() {
  super.didChangeDependencies();
  if (!loaded) {
    AuthContainerState data = AuthContainer.of(context);
    data.isAuthenticated().then((authenticated) {
      setState(() {
        authenticated = authenticated;
        loaded = true;
      });
    });
  }
}

Another way would be to schedule the data fetch in initState with SchedulerBinding. You can find the docs here

SchedulerBinding.instance.addPostFrameCallback((_) {
  // your login goes here
});

Note: remember the didChangeDependencies will be called whenever the state or dependencies of any parent InheritedWidget changes. Please look at the docs here.

Hope this helps!


While the answer by @hemanth-raj is correct, I would actually advocate a slightly different way of doing this. Instead of constructing the AuthContainer with no data, you could actually do the user session loading before you construct your widgets and pass the data in directly. This example uses the scoped_model plugin to abstract away the inherited widget boilerplate (which I highly recommend over writing inherited widgets manually!) but is otherwise pretty similar to what you've done.

Future startUp() async {
  UserModel userModel = await loadUser();
  runApp(
    ScopedModel<UserModel>(
      model: userModel,
      child: ....
    ),
  );
}

void main() {
  startup();
}

This is more or less what I do in my app and I haven't had any problems with it (although you'd probably want to put in some error handling if there's any chance of loadUser failing)!

This should made your userState code much cleaner =).

And an FYI, what I've done in my UserModel is have a bool get loggedIn => ... that knows which information needs to be in there to tell whether the user is logged in or not. That way I don't need to track it separately but I still get a nice simple way to tell from outside the model.