How to Use InheritedWidget in Flutter

Darpan Vithani - Jun 16 '23 - - Dev Community

InheritedWidget provides a way to share data across the widget tree in Flutter. It serves as a container for data that can be accessed by any descendant widget in the hierarchy. Whenever the data within the InheritedWidget changes, it triggers a rebuild of all the dependent widgets in the subtree.

However, besides InheritedWidget, there are two other subclasses, InheritedNotifier and InheritedModel, that offers unique approaches to sharing data in Flutter.

In this article, we will explore each of the subclasses and how they can be implemented by code.

Table of contents

  • What is InheritedNotifier?
    • Defining the Listenable class
    • Creating InheritedNotifier Class
    • Update the state
    • Using the InheritedNotifier
    • Key Points
  • What is InheritedModel?
    • Creating the InheritedModel Class
    • Using the InheritedModel
    • Key Points
  • Conclusion

What is InheritedNotifier?

InheritedNotifier is a subclass of InheritedWidget that combines the capabilities of InheritedWidget and ChangeNotifier. It propagates changes from a ChangeNotifier to descendant widgets. By wrapping ChangeNotifier with InheritedNotifier, you can automatically rebuild dependent widgets whenever the ChangeNotifier triggers updates using notifyListeners().

When creating an InheritedNotifier, you need to provide a Listenable object as its notifier parameter, such as ValueNotifier for simple objects or ChangeNotifier for complex objects.

To better understand the concept, let’s implement the demo.

For full demo access, check out Canopas Blog.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player