Managing Flutter Application State With InheritedWidgets

If the Theme is rebuilt with a new and different ThemeData value, then all of the widgets that referred to it with Theme.of() are rebuilt automatically.It’s easy enough to use a custom InheritedWidget subclass in the same way, as a host for the application’s model..This InheritedWidget subclass is called ModelBinding because it connects the application’s widgets to the model.View the complete ModelBinding v0 example.The updateShouldNotify method is called when the ModelBinding is rebuilt..If it returns true, then all of the dependent widgets are rebuilt.The BuildContext inheritFromWidgetOfExactType() method is used to lookup an inherited widget..Because it’s a little ugly, and for other reasons that will become apparent later, it’s usually wrapped in a static method..Adding the lookup method to the Model class makes it possible to retrieve the model from any descendant of ModelBinding with: Model.of(context):Now ViewController can be stateless and its reference to the model becomes:View the complete ModelBinding v0 example.Any descendant of ModelBinding can do the same thing, there’s no need to pass the Model downwards..If the model changes then dependent widgets like ViewController are rebuilt automatically.The ModelBinding itself must be built by a stateful widget..To change the model, that stateful widget must be rebuilt by calling its setState method..Now the top level App widget becomes stateful and a callback that updates the model must be passed along to the ViewController.View the complete ModelBinding v0 example.In this case, Model is just a simple immutable value, so replacing it is as simple as assigning a new currentModel..Replacing it could be more complicated, for example if the model contained objects that required lifetime management, replacing the model might require disposing parts of the old model.InheritedWidget Version 0 LimitationsOn the upside, the InheritedWidget version of our model binding makes it easy for widgets to refer to the model and it automates rebuilding those “dependent” widgets when the model changes.On the downside, it’s still necessary to plumb an updateModel callback down through the widget tree, to widgets that need to change the model.Binding to the Model with InheritedWidget, Version 1This version of the InheritedWidget approach for binding widgets to a model simplifies model updates..Now any descendant of ModelBinding can get the model as well as update it, and there’s no need to pass around a model specific callback.So, as before, any descendant of ModelBinding can get a model value with Model.of(context), and by doing so become an automatically rebuilt model dependent..Now any descendant of ModelBinding can update the model with Model.update(context, newModel)..Which is nice.To enable rebuilding the model with the static Model.update() method, it’s necessary to introduce an extra stateful widget.. More details

Leave a Reply