[Flutter] initState v/s didChangeDependencies methods
In an attempt to solve a bug in my code, I stumbled onto the didChangeDependencies
method. While it did not solve my problem, it significantly expanded my understanding on the flutter lifecycle methods. Let me share my understanding.
If you have been in the Flutter world for a while now, you must have heard of the initState
method, but what have you ever wondered what didChangeDependencies method is about and how it differs from initState
.
Well let us find out.
initState
in its natural form is called when a Stateful Widget is created and when data needs to be initialised before the widget builds for the first time.
On the other hand, didChangeDependencies
is called when a dependency on the state object changes. such as an inherited widget. Therefore, what makes it useful is that it can be called multiple times during the lifecycle of the widget.
So, why does it matter?
While initState
method might be perfect for loading data initially, didChangeDependencies
offers a dynamic range. For instance, after loading our data in an init state, the context from which the data was loaded might no longer be available. Therefore didChangeDependencies
ensures that our data is always up to date by updating it every time there is a change in the widget's dependencies. This method is crucial because it receives the updated context right after initState
, helping to maintain accurate and current data throughout the widget's lifecycle.
And this is it! I hope this better helps you understand intiState and didChangeDependencies so that you can apply it in your future projects.
About Me
I am Zaahra, a Google Women Techmakers Ambassador who enjoy mentoring people and writing about technical contents that might help people in their developer journey. I also enjoy building stuffs to solve real life problems.
To reach me:
LinkedIn: https://www.linkedin.com/in/faatimah-iz-zaahra-m-0670881a1/
X (previously Twitter): _fz3hra
GitHub: https://github.com/fz3hra
Cheers,
Umme Faatimah-Iz-Zaahra Mujore | Google Women TechMakers Ambassador | Software Engineer