Inherited widgets

Besides statelessWidget and statefulWidget, there is one more type of widget in the Flutter framework, InheritedWidget. Sometimes, one widget may need to have access to data up the tree, and in such a case, we would need to replicate the information down to the interested widget. This process is shown in the following diagram:

Let's suppose some of the widgets down the tree need to access the title property from the root widget. To do that, with statelessWidget or statefulWidget, we would need to replicate the property in the corresponding widgets and pass it down through the constructor. It can be annoying to replicate the property on all child widgets so that the value reaches the interested widget.

To address this problem, Flutter provides the InheritedWidget class, an auxiliary kind of widget that helps to propagate information down the tree as shown in the following diagram:

By adding a InheritedWidget to the tree, any widget below it can access the data it exposes by using the inheritFromWidgetOfExactType(InheritedWidget) method of BuildContext class that receives an InheritedWidget type as parameter and uses the tree to find the first ancestral widget of the requested type.

There are some very common appearances of the usage of InheritedWidget in Flutter. One of the most common uses is from the Theme class, which helps to describe colors for a whole application. We will look at it in Chapter 5, Handling User Input and Gestures.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.70.93