-1.6 C
New York
Thursday, February 2, 2023

Working with didChangeDependencies() in Flutter

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. Advertisements

Examples

The point here is that you cannot use context inside the initState() method but can use it with 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) {
   /* */
}

Advertisements3. 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:

Advertisements

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

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles