Problem Statement
When and why would you use didChangeDependencies() instead of initState()? Provide examples.
Explanation
Use didChangeDependencies() instead of initState() when your initialization code depends on InheritedWidgets or BuildContext. InitState() is called before the widget is fully integrated into the tree, so context-dependent operations like Theme.of(context), MediaQuery.of(context), or Provider.of(context) might not work correctly or could cause unnecessary rebuilds.
DidChangeDependencies() is called after initState() when dependencies are first established, and again whenever those dependencies change. For example, if you initialize a color based on theme data, do it in didChangeDependencies() so it updates when the theme changes. Or if you start a subscription based on Provider data, didChangeDependencies() ensures you get the latest data and can react to changes.
Example: Loading localized strings with AppLocalizations.of(context) should happen in didChangeDependencies() because the localization might change during the app's lifetime. Similarly, initializing animations or controllers based on MediaQuery data (like screen size) should be in didChangeDependencies() to handle screen rotation or window resizing.
Be careful with didChangeDependencies() because it can be called multiple times. Use flags to avoid repeating expensive initialization: check if resources are already initialized before reinitializing them. For one-time initialization that doesn't depend on context, always prefer initState(). For context-dependent initialization that must update when dependencies change, use didChangeDependencies(). Understanding this distinction prevents bugs related to theme changes, locale changes, or provider updates.
