Working with didChangeDependencies() in Flutter

Updated: January 30, 2023 By: Napoleon 3 comments

In Flutter, didChangeDependencies() is called only a few moments after the state loads its dependencies. With this method, we can use context outside of build().

There’re several situations you need to call didChangeDependencies(). Below are a few examples.

Examples

The point here is that you cannot use context inside the initState() method but can use it within the didChangeDependencies() method.

1. You use Provider for state management and need to use it outside of build():

@override
void didChangeDependencies() {
    // Provider.of<>(context)
    super.didChangeDependencies();
}

Widget build(BuildContext context) {
   /* */
}

2. You want to use MediaQuery.of(context) outside of build():

@override
void didChangeDependencies() {
    // MediaQuery.of(context)
    super.didChangeDependencies();
}

Widget build(BuildContext context) {
   /* */
}

3. You want to use Theme.of(context) outside of build():

@override
void didChangeDependencies() {
    // Theme.of(context)
    super.didChangeDependencies();
}

Widget build(BuildContext context) {
   /* */
}

Under the hood

According to the Flutter official docs, didChangeDependencies() is called when a dependency of the State object changes or immediately after initState(). It is safe to call BuildContext.dependOnInheritedWidgetOfExactType from this method.

The dependOnInheritedWidgetOfExactType() method obtains the nearest widget of the given type T, which must be the type of a concrete InheritedWidget subclass, and registers this build context with that widget such that when that widget changes (or a new widget of that type is introduced, or the widget goes away), this build context is rebuilt so that it can obtain new values from that widget.

Final Words

We’ve covered some common use cases of the didChangeDependencies() method. In order to explore more new and awesome features of Flutter, take a look at the following articles:

You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.

Subscribe
Notify of
guest
3 Comments
Inline Feedbacks
View all comments
Tada
Tada
1 year ago

Read some other articles, this is the same, can not point out what is the “dependencies”?

Suragch
Suragch
3 years ago

context isn’t passed in as a parameter to didChangeDependencies. Where you are you getting it?

A Goodman
Admin
A Goodman
3 years ago
Reply to  Suragch

This method is also called immediately after initState. It is safe to call BuildContext.dependOnInheritedWidgetOfExactType from this method. dependOnInheritedWidgetOfExactType method obtains the nearest widget of the given type T, which must be the type of a concrete InheritedWidget subclass, and registers this build context with that widget such that when that… Read more »

Related Articles