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.
Table of Contents
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.