Both the
initState()
method anddidChangeDependencies()
are executed before thebuild()
method of a state object, so why is the context not available insideinitState()
but available insidedidChangeDependencies()
?According to the official docs,
didChangeDependencies()
is called whenever the dependency of the State object changes. What does dependency mean here, and when does it change? (I am a beginner, so please use layman's term to explain this concept to me. I looked up other similar questions, but was not able to understand this.)Unrelated to this topic, I understand that flutter creates elements and renderObjects for each widget it encounters in the widget tree and if that widget is a statefulWidget, then a state object is also created and a reference to that state object is held inside the element. My question is when are the element, renderObject and state object associated with a widget completely removed from their corresponding trees? Does this happen when the widget is permanently removed from the widget tree, or are they kept even after the widget is removed from the widget tree and some other widget is displayed in its place? For example, let's say that I have a floating action button on my homepage and on clicking that I'm pushing a namedPage onto the stack using the pushNamed method of the Navigator class and displaying a new page. Let's say that the new page is a StatefulWidget which has a state object associated with it, so when I go back to my home page again using the back button, that StatefulWidget is removed from the widget tree, right? Are the State object, element and renderObject associated with that widget destroyed immediately, or does flutter keep them around? If flutter does keep them around for some time, then how does it decide when to destroy those objects?

- 5,257
- 5
- 12
- 34

- 21
- 4
1 Answers
Firstly, you have to understand what is BuildContext
that usually name as context
.
buildContext is: the place in the widget tree in which this widget is placed.
All widgets have a
bool this.mounted
property. It is turnedtrue
when thebuildContext
is assigned. It is an error to callsetState
when a widget is unmounted.
why unsafe to use context in initState
is because the widget is unmounted
. means that the widget doesn't have place in the widget tree.
didChangeDependencies()
: This method is called immediately after initState
on the first time the widget is built.
its safe now because property mounted is true.
for the 3rd, you may know about deactivate()
method. here
this is another answer for full explanation of flutter widget lifecylce :Life cycle in flutter

- 3,491
- 3
- 10
- 30