Navigating StatefulWidgets Part 2
Tags: flutter, programming, dart
Published: 2024-03-22 16:48:14


*A continued look at Flutter’s StatefulWidget, its State and its Lifecycle.*

I’ll continue where I left off in my previous article, [Navigating StatefulWidgets Part 1](https://dev.to/andrious/navigating-statefulwidgets-part-1-2dni), working with the gist, [three_counter_app_with_prints](https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553) and commenting out the list of **return** statements to demonstrate how both the StatefulWidget and its State object behave under certain circumstances in your typical Flutter app. With numerous **print**() methods in and among the code, we’ll get some good insight as to what event functions fire in the Flutter framework (from user or system interaction) and in what order.

Let’s begin.

## Your Inheritance

The next two **return** statements involve an Inherited Widget. State objects will fire a particular event function called, _didChangeDependencies_, because an InheritedWidget is now involved, and I’ll walk through the whole sequence of Flutter framework function calls that finally result in the **build**() functions of isolated and dispersed Stateless & StatefulWidgets being called again, and thus, rebuilding them seemingly by magic.

![](https://cdn-images-1.medium.com/max/4180/1*DYDLmOvFWdOVQdXGRyJqDQ.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L92">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4178/1*KGxGGCrWJCDjd7Hx8z3URA.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L92">three_counter_app_with_prints.dart</a></figcaption>

Let’s look at the first screenshot above. The InheritedWidet is taking in the StatefulWidget, *_FirstPageInherited*. Yes, it’s another copy of the original StatefulWidget, *FirstPage*, and reproduced again merely for demonstration purposes. It has a FirstCounter StatefulWidget equivalent named, *_FirstCounterInherited*, and it has been modified to better demonstrate an InheritedWidget’s effect on StatefulWidgets.

Note, that the keyword, **const**, is used to make the _FirstPageInherited class a constant defined at compile-time. Back in part one of this article, we saw the necessity of the **const** keyword in calling such StatefulWidgets, so I won’t hash over that again. We know it’s important that the **const** keyword be there. Comment it out on your own time to remember why.

## Depend On It

So, you now know the ‘Inherited’ version of FirstCounterState does things a little differently, and yet, judging from the video and console screen below, it appears to be behaving as in part one of this article. The FirstCounter  button is tapped three times, and we get a count up to three:

![](https://cdn-images-1.medium.com/max/3766/1*fXwJEpSDxTKvkdMhsLboQw.png)

![](https://cdn-images-1.medium.com/max/2000/1*3igSqXfsBee7oWSzKbcTpQ.gif)

Yes, but that console screen above is from the first article. It’s not using the _FirstCounterInheritedState class. It’s using the original FirstCounterState class. The second screenshot below uses the _FirstCounterInheritedState class, and there’s a difference. Tap on the screenshots below to zoom in for a closer look.

![](https://cdn-images-1.medium.com/max/3766/1*fXwJEpSDxTKvkdMhsLboQw.png)

![Non-inherited version vs. Inherited version](https://cdn-images-1.medium.com/max/4992/1*yDIFf5OxLz-MYxsrzcJ_fA.png)

So, a button press causes the ‘HomePage’ State object to call its **setState**() method. Hence its **build**() function is called soon after. Next, the _FirstCounterInheritedState’s **build**() function is called updating the count, but not before calling its **didChangeDependencies**() method. 
Do you know why? 
It’s because the StatefulWidget, *_FirstCounterInherited*, is a ‘dependent’ to some InheritedWidget (actually its Element is) that was called again when the Home Page was rebuilt again. Do you follow?
The first screenshot below is of the _FirstCounterInheritedState class. When the button is pressed, indeed, it’s the Home Page State object that calls its **setState**() method: `homePageState.setState((){});`
The second screenshot is of that InheritedWidget. Granted, not much to it, but it gets the job done.

![](https://cdn-images-1.medium.com/max/4182/1*udNydWyXjfe7_wRssiENEw.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L1182">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4180/1*KkLdPCHYSD-EyzAcQPnuRw.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L1522">three_counter_app_with_prints.dart</a></figcaption>

In the first screenshot below you readily see the InheritedWidget being called again in the HomePageState object. In the second screenshot, you see in the _FirstCounterInheritedState object how its StatefulElement object, _context_, becomes dependent on that InheritedWidget. Still follow?

![](https://cdn-images-1.medium.com/max/4000/1*PxjdwMwulhHZcd1NCIL8Sw.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L92">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4166/1*c7I45aARpBFDHMucFRSqrQ.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L1156">three_counter_app_with_prints.dart</a></figcaption>

## No Inheritance? No Change 

As a quick aside, I’ll comment out that ‘dependency’ line in the _FirstCounterInheritedState class, and we can see what happens. The FirstCounter continues to increment its counter, but its **build**() function is not called again — the interface is not updated. Simple as that. Remember, it’s being called with the **const** keyword (see the second screenshot below) and so now there’s no means for it to be rebuilt, and so the number displayed remains at zero. That dependency would overcome this.

![](https://cdn-images-1.medium.com/max/4180/1*BesOCgkZYehcQi8hQXWe2Q.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L1155">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4184/1*SJIG-xdjZS5U0uVQrkW-gg.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L970">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/2000/1*zfq030b6M2xSkZ_btOZOAw.gif)

## Inherit The State

Let’s do a walkthrough of the Flutter framework a bit to show you how this is all made possible. I’ve returned the ‘dependency line’ back and will quickly show you what happens when this function is called.

`context.dependOnInheritedWidgetOfExactType<_InheritedWidget>();
`
The second screenshot below is of that function itself deep in the Flutter framework. You see, Flutter makes note of all the InheritedWidgets that may exist on a particular branch of the Widget tree and records them (actually records their InheritedElement counterpart) in the Map variable, *_inheritedElements*.

![](https://cdn-images-1.medium.com/max/3000/1*4Kbmq9hFe1pAgYdWEAsdFg.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L1156">three_counter_app.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4182/1*SyvrsCgNQFOh_BwXnvvxqg.png)
<figcaption><a href="https://github.com/flutter/flutter/blob/b09ca497bb66564d7cca35b0ddb6db49b8855947/packages/flutter/lib/src/widgets/framework.dart#L4767">framework.dart</a></figcaption>

That Map variable is simply looked up by the key for an  InheritedWidget of type, T. In this case, T is of type, *_InheritedWidget.* If found, that InheritedWidget is returned by the function, but not before its InheritedElement counterpart records the dependency. 

_FirstCounterInheritedState’s StatefulElement object records the InheritedWidget in its Set variable, *_dependencies*, and then the _InheritedWidget’s own InheritedElement records the StatefulElement object itself into its  Map variable, *_dependents*. See the screenshots below.

`Set<InheritedElement>? _dependencies;
 Map<Element, Object?> _dependents;`

![](https://cdn-images-1.medium.com/max/4180/1*k20DMrgCJuW09q6MR36k-g.png)
<figcaption><a href="https://github.com/flutter/flutter/blob/b09ca497bb66564d7cca35b0ddb6db49b8855947/packages/flutter/lib/src/widgets/framework.dart#L4767">framework.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4000/1*p1Yjyw3-61bW7soxYgmKIQ.png)
<figcaption><a href="https://github.com/flutter/flutter/blob/b09ca497bb66564d7cca35b0ddb6db49b8855947/packages/flutter/lib/src/widgets/framework.dart#L5980">framework.dart</a></figcaption>

Now, when the InheritedWidget is called again, all the widgets referenced within that Map object, _dependents_,will be ‘rebuilt’. I’ll show you.

In the first screenshot below, when the InheritedWidget is called again, its InheritedElement object calls its **updated**() method.  There,  its InheritedWidget calls its **updateShouldNotify**() function. You’re able to override that function and dictate if the process continues. If that function returns true, the process continues, and eventually the InheritedElement’s **notifyClients**() method is called to iterate through that Map object, *_dependents*. See the second screenshot below.

![](https://cdn-images-1.medium.com/max/4176/1*lfjmuwzj89oPhBl5CKyMtg.png)
<figcaption><a href="https://github.com/flutter/flutter/blob/b09ca497bb66564d7cca35b0ddb6db49b8855947/packages/flutter/lib/src/widgets/framework.dart#L6054">framework.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4162/1*n2eFwj8mdKLOzH7pcO5_2g.png)
<figcaption><a href="https://github.com/flutter/flutter/blob/b09ca497bb66564d7cca35b0ddb6db49b8855947/packages/flutter/lib/src/widgets/framework.dart#L6083">framework.dart</a></figcaption>

The screenshots below depict the next few functions called. 
Each Element object, *dependent*, will be called in turn which leads to calling its **markNeedsBuild**() method. See the second screenshot below. It’s the very same function called by a State object’s **setState**() method. Note, after all this, the corresponding State object’s **didChangeDependencies**() method is called indicating the State object is going to be rebuilt because of an InheritedWidget. 
And there you have it.

![](https://cdn-images-1.medium.com/max/4182/1*KCPCo9jdDd5VGivkTMcILA.png)
<figcaption><a href="https://github.com/flutter/flutter/blob/b09ca497bb66564d7cca35b0ddb6db49b8855947/packages/flutter/lib/src/widgets/framework.dart#L6028">framework.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4182/1*grqhYMKIQINF4MoItffUhA.png)
<figcaption><a href="https://github.com/flutter/flutter/blob/b09ca497bb66564d7cca35b0ddb6db49b8855947/packages/flutter/lib/src/widgets/framework.dart#L4876">framework.dart</a></figcaption>

![](https://cdn-images-1.medium.com/max/4182/1*Y8cU_DdyqbLtPj0VLG_Swg.png)
<figcaption><a href="https://github.com/flutter/flutter/blob/b09ca497bb66564d7cca35b0ddb6db49b8855947/packages/flutter/lib/src/widgets/framework.dart#L5768">framework.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4186/1*keRQQzPObwl6uBHzA0Yx8Q.png)
<figcaption><a href="https://github.com/flutter/flutter/blob/b09ca497bb66564d7cca35b0ddb6db49b8855947/packages/flutter/lib/src/widgets/framework.dart#L5644">framework.dart</a></figcaption>

## Constantly No Inheritance

An InheritedWidget usually takes in a non-constant parameter and so are not eligible to have a constant constructor and be called with the **const** keyword. That’s a good thing since adding the keyword in this case (see below) makes this InheritedWidget simply worthless. It’s compiled and provides a Widget at runtime — nothing more. When the HomePage State object’s **build**() function is called again and again counters are incremented, but the interface is immutable so only zeros will ever be displayed. You shouldn’t find yourself calling an InheritedWidget with the **const** keyword very often. It’s true power will not be much good to you.

![](https://cdn-images-1.medium.com/max/3000/1*ajZm1wQCajgeyLBV3UoILQ.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L92">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4200/1*99mVpCDIUS3AWw9UZcUR9Q.png)

![](https://cdn-images-1.medium.com/max/2000/1*zhp3zuv7zlzX02AxEKJFSg.gif)

## The Next Page

We should turn now to the ‘Second Page’ StatefulWidget displaying its counter on a separate screen altogether. It’s brought up using the Navigator class’s **push**() function. More complex apps will no doubt have the Navigator class handling a great number of separate screens represented on the Widget tree. Each is handled as a separate branch.

This is by no means an exaggeration, that SecondPage StatefulWidget, because it's working with the Navigator class, is situated on a ‘separate’ branch on the Widget tree. See below. As such it has no direct access via the Widget tree to the original three StatefulWidgets ( HomePage, FirstPage and FirstCounter). None.

That’s a problem.

![](https://cdn-images-1.medium.com/max/4000/1*2X3wowk1nAbDHBGuAgaSKQ.png)

As you by now realized, this app has been turning to the Widget tree to retrieve, for example, the Home Page’s State object to readily increment its title bar counter from the FirstPage StatefulWidget. 
See below.
However, there’s no such luck when attempting to access that counter from the Second Page’s State object. Both function calls in the second screenshot below will return null. The StatefulWidgets, *HomePage*, and *SecondPage* simply don’t reside in the same branch. So how then do you access the Home Page’s State object from the Second Page?

![](https://cdn-images-1.medium.com/max/4188/1*MYzyOsghmox5opY7HZo1MQ.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L630">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4182/1*oCL9lpupA_krqYDxsSsk8w.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L472">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/2000/1*IzeOOVNgHBfFKoaYMM91oA.png)


Offhand, you could explicitly pass them as parameters to the SecondPage StatefulWidget in some fashion. Of course, you’ve other options. That’s why you see several third-party State Management solutions out there (i.e. Bloc, RiverPod, MobX, etc.). Of course, it’s not their sole reason, but these packages do provide a means to transverse this disconnect between branches allowing specific data to be shared by multiple screens. I’ll do the same here but using a very minimalist approach — so as not to distract you from the topic at hand. 

## State Control

I just whipped up a ‘State Controller’ class that simply takes in one State object so that it can then be manipulated by an otherwise out-of-reach State object. You'll see what I mean next.

The first screenshot is of the class called, *StateController*. The second screenshot is in the HomePageState class where its very reference is collected by this State Controller, and the third screenshot is where, by using this State Controller, the HomPageState class object is then utilized in the State class, *SecondPageState*. A simple approach.

![](https://cdn-images-1.medium.com/max/4180/1*eUSKeE-x83cFSd2rKwOnRA.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L1446">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4182/1*94ZXjzpAM8Fiwk0HEEHcuQ.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L67">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4182/1*mxilNwfwk5ngDlBeBS4yMQ.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L472">three_counter_app_with_prints.dart</a></figcaption>

As you see in the screenshots below, this Controller class allows for all the functions and features of the State object, *HomePageState*, to be accessed — particularly its instance field, *counter*. It does this simply by implementing Flutter’s State class and the mixin, *CounterState*:

`class StateController implements State, CounterState {`

![](https://cdn-images-1.medium.com/max/4190/1*_-EslINxD--kW4foEgT39w.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L1507">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/3000/1*XqslCJQa_lC0FHJ8HJ5C2Q.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L212">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/2000/1*D0ptrgeJpv-0SiMM6tD8GQ.gif)

So, as you see in the video, the SecondPage StatefulWidget can then easily manipulate the HomePage’s counter like the FirstPage StatefulWidget does. For that matter, any Widget could then do the same from any screen.

## Take Me Home

Finally, let’s step back a bit and take a closer look at the Home Page and its Titlebar counter. It’s a piece of mutable data situated in the Home Page’s State object created at the start of this app. And yet, it is updated and changed by other State objects further along the Widget tree and in other screens altogether. In more complex apps, this is going to be a thing.

In the video below, the button, *Title Counter*, is tapped three times and the title bar is updated accordingly. Let’s see how that’s done.

![](https://cdn-images-1.medium.com/max/4164/1*ztf0EMW1LSFdu_k2Grgb_w.png)

![](https://cdn-images-1.medium.com/max/2000/1*mlWeiWoQPmFcnVOvhosO3w.gif)

Now remember, there are currently two arrangements being showcased here. One takes advantage of an InheritedWidget, the other approach does not. Each arrangement comes about depending on which **return** statement is used. You can see them both in the two screenshots below.

![](https://cdn-images-1.medium.com/max/4000/1*FCzZMD_Xa2oB9_NcY54jMw.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L92">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/3000/1*56P1JLz7g1I1zc7SbL3Qow.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L92">three_counter_app_with_prints.dart</a></figcaption>

I reluctantly created yet another copy of the SecondPage StatefulWidget as there are, because of the InheritedWidget, subtle differences between these two arrangements. With this extra copy, you can readily them. The next few screenshots are paired up to highlight these differences.

In the first screenshot below, without the InheritedWidget involved, the SeconPageState object merely rebuilds itself with its **setState**() method. In the other approach, taking advantage of an InheritedWidget, the HomePageState object’s **setState**() method is explicitly called (so to call its InheritedWidget again) with the line, con.setState((){});
See the second screenshot below.

![](https://cdn-images-1.medium.com/max/4170/1*e1l8mmhYQEs9Y5wPnivwPw.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L526">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4158/1*ntT6q6zE0nHiPaXJ-8ebAQ.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L1341">three_counter_app_with_prints.dart</a></figcaption>

Now, look below at the next pair of screenshots as a consequence of what’s above. Without the InheritedWidget, the Titlebar count has to be explicitly updated with a **setState**() method call after the Navigator.**push**() function. Otherwise, the count will not be updated once you’ve left the SecondPage and returned to the FirstPage. See the first screenshot below.

In the second screenshot below, the InheritedWidget implementation already updates the FirstPage StatefulWidget with every press, so the **setState**() is not necessary. Again, those third-party State Management solutions would have their own varied approach to all this.

![](https://cdn-images-1.medium.com/max/4192/1*LnuWJhwlaa9eBMpTT-aBgQ.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L708">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4170/1*c0TG6tsGuDUqD1m6hCO24g.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L1031">three_counter_app_with_prints.dart</a></figcaption>

See for yourself below. In either case, commenting out the appropriate line will result in returning from the Second Page having incremented the Titlebar count, and yet its change is not updated. It’s been incremented, to be sure. However, the interface back from the Second Page has not yet been rebuilt.

![](https://cdn-images-1.medium.com/max/4184/1*Y1JO1qBH0qABK09pi9IyDA.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L230">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4178/1*-Ng7v7iRyaSWOMSoTWMRBA.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L212">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/2000/1*iz5NaLlNdVQ1dEiO5tdNzA.gif)

## Less Is More

In the first screenshot below, (with no InheritedWidget) since the First Page’s State object is explicitly called to rebuild using its **setState**() method, the Titlebar counter is simply presented in the **build**() function and will display any changes. A traditional approach. 
However, in the other approach, I’ve taken advantage of an  InheritedWidget, to demonstrate again and again you should not rebuild the whole screen over again (particularly really complex ones with lots of widgets) but just rebuild, in this case, the FirstCounter’s count and the Titlebar’s count when a button is pressed.

![](https://cdn-images-1.medium.com/max/4192/1*4ckEfQGOBsOD7Ohu5Oobhg.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L167">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4186/1*nI1EBKFQrBue3gBtF-z3-g.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L966">three_counter_app_with_prints.dart</a></figcaption>

And so, in the second screenshot above, you see a new StatefulWidget called, *HomeTitle*. Granted, not much to it as you see below, but it gets the job done. Notice it’s called with the **const** keyword? What does that tell you?

![](https://cdn-images-1.medium.com/max/4166/1*pB81XTv3lILvh1UbFopvPg.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L1426">three_counter_app_with_prints.dart</a></figcaption>

When either incrementing the FirstCounter StatefulWidget’s count or the HomePage StatefulWidget’s Titlebar count, the InheritedWidget is indirectly called again. That’s because the HomePageState object’s **setState**() method is called. See below.
Both counters are rebuilt when either of the two buttons are pressed, but only those widgets highlighted below— not the rest of the interface! In my opinion, this is the best reason to use InheritedWidgets. The rest of the interface (with possibly its many many widgets) are left untouched. That’s efficiency and better runtime performance.

![](https://cdn-images-1.medium.com/max/4174/1*bQFvgbkHDPMavCaF1FLG1Q.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L1185">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4182/1*7Zh4IgUVZ3w0ImeHIh8Umg.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L1342">three_counter_app_with_prints.dart</a></figcaption>
![](https://github.com/Andrious/inheritedwidget_state_mixin_example/assets/32497443/0e635884-b8f6-44a9-869d-ab3f7229e7a8)

## Climb The Tree

As an aside, in many instances, this app has been turning to the Widget tree to retrieve the HomePage’s State object, *HomePageState*. See the first screenshot below. Let’s take a quick peek at the Flutter framework’s inner workings (second screenshot below) to see what’s happening when you use the function, **findAncestorStateOfType**().

![](https://cdn-images-1.medium.com/max/4182/1*hjsBLFlDJ0g2WBWPIU5edQ.png)
<figcaption><a href="https://gist.github.com/Andrious/cf3bc3ebe5463054fb320938b7853553#file-three_counter_app_with_prints-L947">three_counter_app_with_prints.dart</a></figcaption>
![](https://cdn-images-1.medium.com/max/4168/1*_vVvbe9aNt8NiIgvCNl7xQ.png)
<figcaption><a href="https://github.com/flutter/flutter/blob/b09ca497bb66564d7cca35b0ddb6db49b8855947/packages/flutter/lib/src/widgets/framework.dart#L4823">framework.dart</a></figcaption>

The term, Widget tree, is a bit misleading when going this deep into the Flutter framework. At this scope, it’s an Element tree. Each StatefulWidget has a StatefulElement counterpart, each InheritedWidget has an InheritedElement counterpart, each StatelessWidget has a StatelessElement, etc.

Each Element object has a reference to its parent Element. You can see that reference in the function above. The parent element is stored in the field called, _parent. In Flutter, this results in some really long Linked Lists. Each such list represents one branch of this so-called tree. 

The **findAncestorStateOfType**() function simply goes back up through the parent Elements looking for one of type, *StatefulElement*. See below. Each StatefulElement has a reference to its State object with the instance field, *state*. If one of type, *T*, is found, that field is cast to that specified type, *T*, and ‘[Bob’s your uncle](https://en.wikipedia.org/wiki/Bob%27s_your_uncle)’!

![](https://cdn-images-1.medium.com/max/4000/1*04VRjCeB-NZnE-TemMkxQA.png)
<figcaption><a href="https://github.com/flutter/flutter/blob/b09ca497bb66564d7cca35b0ddb6db49b8855947/packages/flutter/lib/src/widgets/framework.dart#L4823">framework.dart</a></figcaption>

Fortunately, such a ‘brute force’ kind of algorithm is not too expensive on CPU cycles in this case. After all, HomePage is the ‘grandparent’ of the FirstPage StatefulWidget in the Element tree. See below. It’s a convenient way to access your app’s State objects. However, the Flutter team does suggest the **findAncestorStateOfType**() function be used judiciously: 

*/// Calling this method is relatively expensive (O(N) in the depth of the
/// tree). Only call this method if the distance from this widget to the
/// desired ancestor is known to be small and bounded.*

![](https://cdn-images-1.medium.com/max/2000/1*OrJx17ubP0zt3DQ_mDOqrA.png)

![](https://cdn-images-1.medium.com/max/2000/1*D9kSbTqCfeysVaSaEtcdPA.png)

Yet another reason those third-party State Management solutions are so popular. They also allow you quick and reliable access only the State objects you’re concerned with.

## Just Scratching The Surface

The second screenshot above depicts once again the Navigator class responsible for presenting the first screen, *HomePage*, in this humble little counter app. And yet, this humble little app has been sitting on top of an already complicated Flutter framework with many StatefulWidgets starting up other StatefulWidgets.

Looking at the second screenshot, you might ask yourself, ‘How many widgets are between that Navigator class and the HomePage StatefulWidget and linked together in the Element tree?’

Using my IDE, I counted about 50 Elements of different sorts between those two widgets. See below. About 20 are StatefulWidgets, 11 are InheritedWidgets and 4 are StatelessWidgets — and those are only the ones I readily recognize as such Widgets!


![](https://github.com/Andrious/inheritedwidget_state_mixin_example/assets/32497443/c11d986d-6904-4877-a6db-1693a66c1b49)

Now, imagine the true number of Widgets involved in the whole app?! That humble little app:

![](https://cdn-images-1.medium.com/max/4000/1*2X3wowk1nAbDHBGuAgaSKQ.png)



Cheers.

[→ Other Stories by Greg Perry](https://dev.to/andrious)