When to use InheritedWidget, and when not to

63 Views Asked by At

I am currently writing a library (for fun only) and I want to put something (let's call it a 'container') at the top of the widget tree so that it can be looked up by any widget (actually only widgets from my library will only even want to look it up). Changes to the container will not cause any widgets to rebuild directly, it is there to just keep data.

So no I need a way to make this container available in the tree. I would like to learn and NOT use packages like Provider. And I have a dilemma - I looked at the implementation of various Flutter widgets, and each one is different:

  • Localizations is a StatefulWidget whose build() creates an InheritedWidget and passes data from the state to the inherited widget.
  • Theme is a StatelessWidget but creates InheritedWidget in its build().
  • Navigator is a StatefulWidget but doesn't even use InheritedWidget at all.

I bet the more I look, the more solutions I will find.

I managed to implement this propagation down the tree in 2 ways:

  1. StatefulWidget + InheritedWidget combo (like Localizations).
  2. StatefulWidget without InheritedWidget (like Navigator).

Solution number 2 is shorter (as there is no extra InheritedWidget) and it uses the context.findAncestorStateOfType<T>() method and gets the 'container' from the state, while solution number 1 uses context.getInheritedWidgetOfExactType<T>() and gets the container from the InheritedWidget it finds. In both solutions the container is created in the state (so that it is preserved when the tree is rebuilt); in solution 1 the created InheritedWidget gets a reference to this container to propagate down the tree.

Both solutions work, and I fail to see when I would use which. Flutter sources, as mentioned, are not helping with this confusion. The only difference in my case I can see is that context.getInheritedWidgetOfExactType is O(1), and context.findAncestorStateOfType is O(n). In my library I am leaning towards using InheritedWidget based on this fact. However, doesn't this mean that Navigator.of() is suboptimal, and using InheritedWidget would find the navigator sooner?

When would I use which solution?

0

There are 0 best solutions below