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:
- Best Libraries for Making HTTP Requests in Flutter
- Using Provider for State Management in Flutter
- Using GetX (Get) for Navigation and Routing in Flutter
- Flutter: Showing SnackBar with ScaffoldMessenger
- Flutter: Bottom Sheet examples
- Creating Masonry Layout in Flutter with Staggered Grid View
You can also take a tour around our Flutter topic page and Dart topic page to see the latest tutorials and examples.
Read some other articles, this is the same, can not point out what is the “dependencies”?
context
isn’t passed in as a parameter todidChangeDependencies
. Where you are you getting it?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 »