Sub topic 9
Avoid over-broad inherited widget dependencies
This chapter assumes you know how setState marks an element dirty and how build runs again, which earlier chapters covered. It also assumes you have used MediaQuery.of and Theme.of, and that you can profile a Flutter app in profile mode.
How a dependency is created
An inherited widget is a widget that holds data for the whole subtree below it. Examples are MediaQuery, Theme, Directionality, and InheritedNotifier or provider-style wrappers. A descendant reads the data through its BuildContext.
Most lookups do two things:
- They find the nearest inherited widget of a given type.
- They register the calling element as a dependent of it.
When the inherited widget updates and updateShouldNotify returns true, the framework marks every registered dependent dirty. Each of those elements rebuilds in the next frame. It does not matter whether the widget cared about the part of the data that changed.
So the width of a dependency is the question. If a widget calls MediaQuery.of(context) to read the screen width, it depends on all of MediaQueryData. That includes padding, view insets, text scale, brightness, and orientation. A change to any of them rebuilds the widget.
The keyboard example
The most common cost of broad dependencies is the on-screen keyboard. While the keyboard animates open, viewInsets.bottom changes on every frame. MediaQuery notifies its dependents on every one of those frames. A large screen that calls MediaQuery.of(context) high in the tree rebuilds its entire body for the length of the animation.
Here is a widget with the broad dependency:
import 'package:flutter/material.dart';
class ResponsiveGrid extends StatelessWidget {
const ResponsiveGrid({super.key, required this.children});
final List<Widget> children;
@override
Widget build(BuildContext context) {
// Broad: rebuilds on keyboard, padding, brightness, and text scale changes.
final width = MediaQuery.of(context).size.width;
final columns = width > 600 ? 3 : 2;
return GridView.count(crossAxisCount: columns, children: children);
}
}The only input the widget uses is the width. You can narrow the dependency with one line:
import 'package:flutter/material.dart';
class ResponsiveGrid extends StatelessWidget {
const ResponsiveGrid({super.key, required this.children});
final List<Widget> children;
@override
Widget build(BuildContext context) {
// Narrow: depends on the size aspect only (Flutter 3.10 and later).
final width = MediaQuery.sizeOf(context).width;
final columns = width > 600 ? 3 : 2;
return GridView.count(crossAxisCount: columns, children: children);
}
}MediaQuery is an InheritedModel. A model lets a dependent register for one aspect of the data. sizeOf registers only for the size aspect. When the keyboard opens, MediaQuery checks each dependent's registered aspects and skips the ones that did not subscribe to viewInsets.
Narrow accessors for MediaQuery
| Instead of | Use | Rebuilds when |
|---|---|---|
| `MediaQuery.of(context).size` | `MediaQuery.sizeOf(context)` | The window size changes |
| `MediaQuery.of(context).padding` | `MediaQuery.paddingOf(context)` | Safe-area padding changes |
| `MediaQuery.of(context).viewInsets` | `MediaQuery.viewInsetsOf(context)` | The keyboard or other system UI insets change |
| `MediaQuery.of(context).orientation` | `MediaQuery.orientationOf(context)` | The orientation changes |
| `MediaQuery.of(context).platformBrightness` | `MediaQuery.platformBrightnessOf(context)` | The system light or dark setting changes |
| `MediaQuery.of(context).textScaleFactor` | `MediaQuery.textScalerOf(context)` | The user changes the text scale |
The ...Of accessors were added in Flutter 3.10, and textScalerOf arrived with the newer text scaling API. Check that your SDK has the one you want. The old MediaQuery.of still works. It is the broadest lookup, so use it only when you really need several aspects at once.
Where you call it matters
Calling a narrow lookup in the wrong place still costs you. If you call MediaQuery.sizeOf(context) in the build method of a large screen widget, the whole screen rebuilds when the size changes. A rotation or a desktop window resize is rare, but it is a large rebuild. When only one small child needs the value, move the lookup into that child, or wrap it in a LayoutBuilder:
import 'package:flutter/material.dart';
class AdaptiveBanner extends StatelessWidget {
const AdaptiveBanner({super.key});
@override
Widget build(BuildContext context) {
// LayoutBuilder depends on the parent constraints, not on MediaQuery,
// so keyboard changes never reach it.
return LayoutBuilder(
builder: (context, constraints) {
final wide = constraints.maxWidth > 600;
return Text(wide ? 'Wide layout' : 'Compact layout');
},
);
}
}Use LayoutBuilder when the layout should follow the space the parent gives the widget. Use MediaQuery.sizeOf when it should follow the window.
Theme lookups
Theme.of(context) registers a dependency on the nearest Theme. Unlike MediaQuery, it has no per-aspect model. Any change to the ThemeData notifies every dependent. Changes are rare in most apps, so this is usually fine. It becomes a problem when you animate a theme, for example with AnimatedTheme or a dynamic color scheme. Then every widget that called Theme.of rebuilds on every frame.
Two things limit the damage:
- Call
Theme.of(context)as low in the tree as you can, in the small widget that uses the color or text style. - Keep subtrees that never read the theme
const, so a theme update that does reach them still skips the rebuild (see the chapter onconst).
Your SDK version may also provide narrower accessors for some Theme values. Look at the Theme class documentation before you build your own.
Writing your own narrow dependency with InheritedModel
If your app has its own inherited widget with several fields, you can give it aspects too. Without them, a change to any field rebuilds every dependent.
import 'package:flutter/material.dart';
enum SettingsAspect { themeMode, locale }
class SettingsModel extends InheritedModel<SettingsAspect> {
const SettingsModel({
super.key,
required this.themeMode,
required this.locale,
required super.child,
});
final ThemeMode themeMode;
final String locale;
static ThemeMode themeModeOf(BuildContext context) {
return InheritedModel.inheritFrom<SettingsModel>(
context,
aspect: SettingsAspect.themeMode,
)!.themeMode;
}
static String localeOf(BuildContext context) {
return InheritedModel.inheritFrom<SettingsModel>(
context,
aspect: SettingsAspect.locale,
)!.locale;
}
@override
bool updateShouldNotify(SettingsModel oldWidget) {
return themeMode != oldWidget.themeMode || locale != oldWidget.locale;
}
@override
bool updateShouldNotifyDependent(
SettingsModel oldWidget,
Set<SettingsAspect> dependencies,
) {
return (dependencies.contains(SettingsAspect.themeMode) &&
themeMode != oldWidget.themeMode) ||
(dependencies.contains(SettingsAspect.locale) &&
locale != oldWidget.locale);
}
}A widget that calls SettingsModel.localeOf(context) is rebuilt only when locale changes. A change to themeMode calls updateShouldNotifyDependent, which returns false for it.
Reading without subscribing
Sometimes a widget needs a value once, for example inside an onPressed callback. It should not rebuild when that value changes. There are two tools:
context.getInheritedWidgetOfExactType<T>()finds the inherited widget without registering a dependency.- With
package:provider,context.read<T>()returns the object without subscribing, andcontext.watch<T>()subscribes.
import 'package:flutter/material.dart';
class SettingsModelReader extends StatelessWidget {
const SettingsModelReader({super.key});
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () {
// One-time read inside a callback: no dependency is registered.
final model = context.getInheritedWidgetOfExactType<SettingsModel>();
debugPrint('Locale at tap time: ${model?.locale}');
},
child: const Text('Log locale'),
);
}
}Dependencies in State objects
A State object can depend on an inherited widget too. Do not read inherited widgets in initState, because the framework asserts that you do not subscribe there. Use didChangeDependencies. The framework calls it once after initState and again each time a dependency notifies.
import 'package:flutter/material.dart';
class SizeAwareLoader extends StatefulWidget {
const SizeAwareLoader({super.key});
@override
State<SizeAwareLoader> createState() => _SizeAwareLoaderState();
}
class _SizeAwareLoaderState extends State<SizeAwareLoader> {
late int _imageWidth;
@override
void didChangeDependencies() {
super.didChangeDependencies();
// Narrow lookup: runs again only when the size aspect changes.
final width = MediaQuery.sizeOf(context).width;
_imageWidth = (width * MediaQuery.devicePixelRatioOf(context)).round();
}
@override
Widget build(BuildContext context) {
return Text('Request images at $_imageWidth px');
}
}If this code used MediaQuery.of(context), didChangeDependencies would run on every keyboard frame. If it also started a network request there, you would fire many requests.
Finding broad dependencies in your code
- Search your code for
MediaQuery.of(,Theme.of(,context.watch<, andProvider.of<with the defaultlisten: true. - For each hit, write down which fields of the result the widget actually reads.
- If the number of fields is small, switch to the narrow accessor, a
context.select, or anInheritedModelaspect. - If the lookup sits in a large
buildmethod, move it into a smaller widget class. - Confirm the change with
debugPrintRebuildDirtyWidgetsor the DevTools rebuild counts, as in the measuring chapter. Open and close the keyboard while you watch the log.
Some rebuilds are not worth removing. A small Text that depends on the whole MediaQueryData and rebuilds a few times per keyboard animation costs almost nothing. Fix the dependencies that sit above large subtrees first.
Common mistakes
- Narrow lookup, wide location. You switched to
sizeOf, but the call is still in the build method of the whole screen, so every resize rebuilds the whole screen. - Mixing broad and narrow lookups. One leftover
MediaQuery.of(context)in the samebuildmethod brings back the broad dependency. - Reading in
initState. This throws in debug mode. Move the read todidChangeDependencies. - Using
readwhere you needwatch. The widget shows stale data. - Missing
updateShouldNotifylogic. An inherited widget that always returnstruenotifies all dependents on every parent rebuild.
Exercise
A checkout screen calls MediaQuery.of(context).padding.bottom in the build method of its top-level widget to place a button above the home indicator. Users report jank while the keyboard opens in a text field on the screen. Explain why the whole screen rebuilds and give two changes that fix it.
Show answer
MediaQuery.of registers a dependency on all of MediaQueryData. While the keyboard animates, viewInsets changes on every frame, so MediaQuery notifies its dependents each frame and the top-level widget rebuilds with everything below it. Fix 1: replace the call with MediaQuery.paddingOf(context).bottom, which depends only on the padding aspect and is not notified by viewInsets changes. Fix 2: move the lookup into a small widget that builds only the button, so a padding change rebuilds just that widget and not the whole screen. Doing both is best.
Exercise
You have an inherited widget with two fields, themeMode and locale. Only a language picker needs locale, but every widget in the app that calls themeModeOf rebuilds when the language changes. What do you change in the inherited widget?
Show answer
Make it an InheritedModel with an aspect enum (for example themeMode and locale). Read each field with InheritedModel.inheritFrom(context, aspect: ...), and implement updateShouldNotifyDependent so it returns true for a dependent only when a field that matches one of its registered aspects has changed. Then the theme-mode readers are skipped when only locale changes.