As we know, a Flutter application manages a tree of widgets that sometimes become a very deep tree of widgets. In this big tree, if you want to pass parameters from root to lower widget. You can do it with the help of the constructor that is perfectly fine for accessing data one level down, maybe even two. But if you're widget tree level is deep and you suddenly need the data from an object in your code from root to lower widget. It'll become complex and lead to a lot of boilerplate code for passing context around, as shown below:
In order to provide a solution for this situation, Flutter provides a special widget called InheritedWidget that defines a context at the root of a sub-tree. It can efficiently deliver this context to every widget in that sub-tree. This widget is specially designed to hold data and to provide it throughout the widget tree, irrespective of its depth. InheritedWidget is the base class for widgets that efficiently propagate information down the widgets tree. All widgets part of that sub-tree will have to ability to interact with the data which is exposed by that InheritedWidget.
class RootWidget extends StatelessWidget { Level - 1 final int postId; final int scopeId; RootWidget(this.postId, this.scopeId); Widget build(BuildContext context) { ...To DO return PostItemWidget(postId, scopeId); } } class PostItemWidget extends StatelessWidget { Level - 2 final int postId; final int scopeId; PostItem(this.postId, this.scopeId); Widget build(BuildContext context) { ...To DO return PostMenuWidget(postId, scopeId); } } class PostMenuWidget extends StatelessWidget { Level - 3 final int postId; final int scopeId; PostMenuWidget(this.postId, this.scopeId); Widget build(BuildContext context) { // repeat ... Levels - n
In order to provide a solution for this situation, Flutter provides a special widget called InheritedWidget that defines a context at the root of a sub-tree. It can efficiently deliver this context to every widget in that sub-tree. This widget is specially designed to hold data and to provide it throughout the widget tree, irrespective of its depth. InheritedWidget is the base class for widgets that efficiently propagate information down the widgets tree. All widgets part of that sub-tree will have to ability to interact with the data which is exposed by that InheritedWidget.