0

I have a BLoC that can be accessed anywhere from any widget within the screen as long as I access it as an inherited widget. However, I want to show a dialog and use the same instance of my model in it. When I try to access my model as an inherited widget I get a null error. It looks like this is due to a new screen using a new context.

Is there a way to allow my model to be used for child screens/dialogs without explicitly passing it in the constructor?

Elforama
  • 512
  • 1
  • 4
  • 16

1 Answers1

0

The entire point of inherited widget is to allow you to access it without having to pass it down through constructors. If you're having to pass it, you're probably not using it as designed.

There are a few things to keep in mind with inherited widgets. The first is that they are immutable; you can't change their data. The second is that there's no direct way to access one by itself.

What you should be doing instead is making a StatefulWidget subclass in your widget tree such that it's higher in the tree than anywhere you would need it. That means that if you have it in one page, then push a new page to the navigator, it isn't going to work, as they are separate branches in the widget tree under the Navigator.

Take a look at this answer for a more in-depth example of how to use an inherited widget. Also, check out the scoped_model package - it eliminates a lot of the boilerplate needed for inherited widgets.

If all you're doing is showing a dialog then returning to the same page though, you shouldn't have to use an InheritedWidget at all - you could just use a simple widget then pass it back afterwards. However, without adding some code to your question it's very hard to tell where you could be going wrong.

rmtmckenzie
  • 37,718
  • 9
  • 112
  • 99
  • Thanks for the response! You're third paragraph is where my issue is. A new screen is a new branch in the widget tree. Despite this, is there a way to share the model between the two branches? I want to allow a hierarchy of model scopes. The only thing I can currently do if have a singleton scope (inherited widget at root of widget tree), and a local scope (the model is scoped to the current navigator branch "screen"). – Elforama Aug 17 '18 at 21:00