1

I've started to learning about Flutter's inherited widgets and i have a question. Why do we need an InheritedWidget if we can get data from context.findAncestorOfExactType? And that updateShouldNotify... Like, it notifies child widgets when some condition is true, and they are anyway running their build methods after InheritedWidget changed, because it's immutable and we can only chage it in some rebuild...

CyberSeal
  • 11
  • 1

1 Answers1

0

InheritedWidget is more useful for build method cases. When you want to get data from an ancestor inside your build method.

From the Flutter API: https://api.flutter.dev/flutter/widgets/BuildContext/findAncestorStateOfType.html

This should not be used from build methods, because the build context will not be rebuilt if the value that would be returned by this method changes. In general, dependOnInheritedWidgetOfExactType is more appropriate for such cases. This method is useful for changing the state of an ancestor widget in a one-off manner, for example, to cause an ancestor scrolling list to scroll this build context's widget into view, or to move the focus in response to user interaction.

Also by doing what you mention, you are coupling Widgets together which is not a good practice at all. Widgets are known to be able to moved from place to place without much modification.

There are many useful things that come from the Inherited Widget. Some of these things are very useful packages, I recommend that you take a look at them.

You can also take a look at the InheritedWidget documentation

Migalv
  • 652
  • 6
  • 19
  • 1
    Can you please, give an example of code, in which we will update value in some widget, but its child (or child of its child, anyway it should be widget, which placed below in the tree) won't rebuilt with new value? I've tried to do some examples like i said, but everytime child-widget were rebuilt with new value from it's ancestor (value were passed from context.findWidgetOfExactType()) – CyberSeal Dec 04 '20 at 19:15