Working with Inherited Widgets in Flutter
Working with InheritedWidgets in Flutter
Inherited Widgets are a powerful tool for working with Flutter applications. They allow developers to pass data and state down the widget tree, without having to write explicit code to do so. Additionally, they make the development of complex layouts easier and can help reduce the amount of boilerplate code.
The basic idea behind Inherited Widgets is that you wrap a Widget up in a type of container called an InheritedWidget. This InheritedWidget can then be accessed by any of its descendent Widgets in the widget tree. In this way, any changes to the state of the InheritedWidget are automatically propagated down to its children and other dependents.
In Flutter, there are a few different types of Inherited Widgets that can be used. These include:
- InheritedModel
- InheritedWidget
- InheritedStatefulWidget
- StatefulInheritedWidget
Inherited Widgets can be useful for a variety of tasks, such as passing data between widgets, sharing global application state, and organizing layouts in a more maintainable way. Let’s take a look at how they work and how you can use them in your own projects.
Using an InheritedWidget
The first step to using an InheritedWidget is to create a new subclass of InheritedWidget:
class MyInheritedWidget extends InheritedWidget {
final String someValue;
MyInheritedWidget({
@required this.someValue,
@required Widget child
}) : super(child: child);
@override
bool updateShouldNotify(MyInheritedWidget oldWidget) {
return oldWidget.someValue != someValue;
}
}
The purpose of this class is to hold some piece of information that can be accessed in its descendants. In this case, it’s a String. The updateShouldNotify method is where you define what constitutes a change in state for this widget. If any changes are detected, then any descendent Widgets that have subscribed to this InheritedWidget will be notified.
To use this InheritedWidget, you can wrap it around any other Widgets in the widget tree like so:
MyInheritedWidget(
someValue: "Some Value",
child: MyWidget()
)
Any widgets nested inside of MyWidget will now be able to access this InheritedWidget's state by using the static of method like so:
final myInheritedWidget = MyInheritedWidget.of(context);
And thus, any changes to this InheritedWidget’s state will be propagated down to all of its descendants.
Conclusion
Inherited Widgets are a powerful and useful tool for working with Flutter apps. They can be used to pass data and state down the widget tree without having to write any additional code, and they make the development of complex layouts much simpler. Give them a try in your own project and see for yourself how they can simplify your workflow!