Sub topic 14
Common pitfalls and how to avoid them
This chapter assumes you have read the earlier chapters of this tutorial. You should know how constraints flow down and sizes flow up, the difference between MediaQuery.sizeOf and LayoutBuilder, and the 600 and 840 logical pixel breakpoints. Here the focus is on the mistakes that show up most often in real apps, how to recognize each one, and how to fix it.
Pitfall 1: Reading the whole window when you need local space
MediaQuery reports the size of the window (more precisely, of the nearest MediaQuery ancestor). A widget in a 300-pixel side pane of a 1200-pixel window still sees 1200. If you pick its layout from MediaQuery, it picks the wide layout inside a narrow pane and overflows.
The rule of thumb:
- Use
MediaQuery.sizeOf(context)for decisions about the whole screen, such as which navigation widget to show. - Use
LayoutBuilderfor decisions about a component, such as how many columns a grid in a pane gets.
A related mistake is calling MediaQuery.of(context).size. of subscribes the widget to every MediaQuery field. When the keyboard opens, viewInsets changes, and every widget that called of rebuilds even though it only needed the width. Prefer the aspect-specific methods:
import 'package:flutter/material.dart';
class WidthProbe extends StatelessWidget {
const WidthProbe({super.key});
@override
Widget build(BuildContext context) {
// Rebuilds only when the size changes, not when the keyboard opens.
final width = MediaQuery.sizeOf(context).width;
final scale = MediaQuery.textScalerOf(context);
return Text('Width: ${width.round()}, scaled 16 = ${scale.scale(16)}');
}
}Pitfall 2: Unbounded constraints
The most common Flutter layout error is "Vertical viewport was given unbounded height" or "RenderFlex children have non-zero flex but incoming height constraints are unbounded". Both have the same cause. A parent gave a child infinite space along an axis, and the child needs a finite size.
Typical triggers:
- A
ListVieworGridViewdirectly inside aColumn. AColumngives its children unbounded height, and a scrollable wants to fill all of it. - An
Expandedinside aColumnthat sits in a scroll view or another unbounded parent. - A
Rowcontaining aTextFieldwith no width limit. - A
LayoutBuilderinside a horizontal scroll view, whereconstraints.maxWidthisdouble.infinity. Comparing infinity against a breakpoint always selects the widest layout.
The fix is to give the child a bound. Wrap the scrollable in Expanded, or put a SizedBox or ConstrainedBox around it:
import 'package:flutter/material.dart';
class HeaderAndList extends StatelessWidget {
const HeaderAndList({super.key});
@override
Widget build(BuildContext context) {
return Column(
children: [
const Text('Header'),
Expanded(
child: ListView.builder(
itemCount: 50,
itemBuilder: (context, i) => ListTile(title: Text('Row $i')),
),
),
],
);
}
}Pitfall 3: Breakpoint logic scattered through the code
If width >= 600 appears in twelve files, someone eventually writes > 600 in one of them, and a window exactly 600 wide shows two different layouts at once. Keep the thresholds in one function, as in the windowSizeFor helper from the breakpoints chapter, and call it everywhere. The same rule applies to the 840 boundary.
Two related mistakes:
- Choosing by device type. A resizable desktop window, split-screen on a tablet, and a foldable all break the idea of "this is a phone". Choose by available width.
- Choosing by orientation. A phone in landscape can be wider than a small tablet in portrait, and a landscape window can still be narrow in split-screen. Width is the signal that matches how much content fits.
Pitfall 4: Losing state when the layout switches
When a window crosses a breakpoint, you swap one widget subtree for another. Flutter matches widgets by type and position, so a different subtree means a new State object. Anything stored inside the old subtree, such as a scroll position, a text field's contents, or a selected item, is gone.
The fix is to keep state above the point where the layout switches. The selection in this list-detail page lives in the page's state, so it survives a resize:
import 'package:flutter/material.dart';
class ListDetailPage extends StatefulWidget {
const ListDetailPage({super.key});
@override
State<ListDetailPage> createState() => _ListDetailPageState();
}
class _ListDetailPageState extends State<ListDetailPage> {
int? _selected;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final list = ListView.builder(
itemCount: 20,
itemBuilder: (context, i) => ListTile(
title: Text('Item $i'),
selected: i == _selected,
onTap: () => setState(() => _selected = i),
),
);
final detail = Center(
child: Text(
_selected == null ? 'Pick an item' : 'Detail for $_selected',
),
);
if (constraints.maxWidth >= 600) {
return Row(
children: [
SizedBox(width: 280, child: list),
const VerticalDivider(width: 1),
Expanded(child: detail),
],
);
}
if (_selected == null) return list;
return Column(
children: [
Align(
alignment: Alignment.centerLeft,
child: TextButton(
onPressed: () => setState(() => _selected = null),
child: const Text('Back'),
),
),
Expanded(child: detail),
],
);
},
);
}
}Use it as the body of a Scaffold, because ListTile needs a Material ancestor. For state that lives inside a widget you must move between positions, such as a video player, give that widget a GlobalKey so Flutter can reparent it instead of recreating it. Use PageStorageKey to preserve scroll offsets.
Pitfall 5: Ignoring text scaling and safe areas
Users can raise the system font size well past 1.0, and a layout tuned at the default scale breaks. Fixed-height containers clip text, and rows with several labels overflow.
- Do not give text a fixed-height parent. Let the height come from the content, or use
ConstrainedBoxwithminHeight. - Wrap row labels in
FlexibleorExpandedand setoverflow: TextOverflow.ellipsisormaxLines. - Use
Wrapinstead ofRowfor groups of chips or buttons that may not fit on one line. - Do not clamp the text scaler to hide the problem. That removes an accessibility feature from the users who need it.
For safe areas, notches, rounded corners and system bars can cover content. Scaffold and AppBar already handle the top inset. If you wrap a whole Scaffold body in SafeArea and also use an AppBar, you may get extra padding at the top. Apply SafeArea to content that sits outside a Scaffold, and use its top, bottom, left and right flags to opt out of sides that are already handled.
Pitfall 6: Platform checks that crash or lie
Platform.isAndroid from dart:io throws an UnsupportedError on the web. Even where it works, it reports the host operating system, not what the user is running in a browser. Use these instead:
Theme.of(context).platformfor the platform the theme targets. Tests can override it withThemeData(platform: ...).kIsWebfrompackage:flutter/foundation.dartto detect the web.
Do not infer input type from the platform either. A tablet may have a mouse, and a laptop may have a touch screen. Handle hover, focus and keyboard shortcuts as additions that work alongside touch.
Pitfall 7: Testing only one size
Widget tests run in a default window of 800 by 600 logical pixels. That is already in the medium range, so a test that never sets a size silently tests the NavigationRail branch of the shell and never the NavigationBar one. Set the size explicitly in each test, and reset it afterwards so one test does not leak its window into the next:
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
void main() {
testWidgets('uses a bottom bar on narrow windows', (tester) async {
tester.view.physicalSize = const Size(400, 800);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(const MaterialApp(home: AdaptiveShell()));
expect(find.byType(NavigationBar), findsOneWidget);
expect(find.byType(NavigationRail), findsNothing);
});
}Set devicePixelRatio as well as physicalSize. The logical width is physicalSize.width / devicePixelRatio, so leaving the ratio at its default of 3.0 turns a 1200-pixel width into 400 logical pixels. Test at least one size on each side of every breakpoint, and test a size exactly on the boundary.
A debugging path for layout errors
When a layout misbehaves, work through the questions below in order.
Quick reference
| Symptom | Likely cause | Fix |
|---|---|---|
| Whole subtree rebuilds when the keyboard opens | `MediaQuery.of(context)` | Use `sizeOf` or `textScalerOf` |
| Wide layout inside a narrow pane | `MediaQuery` used for local layout | Use `LayoutBuilder` |
| "Unbounded height" exception | Scrollable or `Expanded` in an unbounded parent | Bound it with `Expanded` or `SizedBox` |
| Selection lost on resize | State held inside the swapped subtree | Hoist state, add keys |
| `UnsupportedError` on web | `dart:io` `Platform` | `Theme.of(context).platform`, `kIsWeb` |
| Test passes but the narrow layout is broken | Default 800 by 600 window | Set `tester.view` size and ratio |
Exercise
A LayoutBuilder placed inside a horizontal SingleChildScrollView always picks the expanded layout, even in a narrow window. Why does this happen, and how would you fix it?
Show answer
A horizontal scroll view gives its child unbounded width, so constraints.maxWidth is double.infinity, which is greater than every breakpoint. Fix it by taking the width from a bounded source instead, for example MediaQuery.sizeOf(context).width if the whole window is the right reference. You can also move the LayoutBuilder outside the scroll view, or give the scrolled content an explicit width with SizedBox.
Exercise
Your widget test for a shell with a breakpoint at 600 sets tester.view.physicalSize = const Size(900, 600) and expects a bottom bar, but finds the rail. The device pixel ratio was not changed. What is the logical width, and what should you change?
Show answer
The default ratio in tests is 3.0, so the logical width is 900 / 3.0 = 300, which would give the bottom bar. If the test finds the rail, check what the ratio actually is, because the likely cause is a ratio of 1.0 left over from another test that did not reset the view. Set tester.view.devicePixelRatio explicitly in every test, and register addTearDown(tester.view.reset) so settings do not leak between tests.