Search code examples
flutterproviderinherited-widget

Is InheritedWidget should always need to be a child of StatefulWidget?


Things that I know about InheritedWidget?

InheritedWidgets are not rebuilts instead we have to create a new InheritedWidget with a new value. Then inside the updateShouldNotify() method will compare its old and current object and return true or false.

if updateShouldNotify() returns true -> then dependent contexts get rebuild.

if updateShouldNotify() returns false -> then dependent contexts doesn't rebuild.

@override
bool updateShouldNotify(_InheritedCount old) {
  return old.state != state;
}

So every time when we creating a new instance of the previous InheritedWidget will call that updateShouldNotify() method and decided to rebuilt their dependents or not.

What I want to know about InheritedWidget ? (things that I confused)

  1. Does every InheritedWidget need to be wrap with StatefulWidget to creates its new instance of that InheritedWidget ?
  2. Does ChangeNotifierProvider wrap its InheritedWidget (or InheritedProvider) in a StatefulWidget to recreate new InheritedWidget, when ChangeNotifier object sends change notification to its ChangeNotifierProvider() ?

(be kind about how I handle English language)


Solution

  • Indeed, most of the time you will need to wrap an InheritedWidget in a StatefulWidget to cause rebuilds.

    There's an exception when using InheritedNotifier instead of InheritedWidget, but that's fairly rare.

    Does ChangeNotifierProvider wrap its InheritedWidget (or InheritedProvider) in a StatefulWidget to recreate new InheritedWidget, when ChangeNotifier object sends change notification to its ChangeNotifierProvider() ?

    That's similar to what Provider does, yes.

    It doesn't use this exact combination though. Instead Provider implemented a new kind of InheritedWidget: InheritedProvider.

    This InheritedProvider is both a StatefulWidget and an InheritedWidget in a single widget. It's an InheritedWidget with a setState / dispose