Sub topic 13
Testing layouts at different window sizes
This chapter assumes you can write basic testWidgets tests with flutter_test, and that you have the windowSizeFor helper, AdaptiveBody and AdaptiveShell from earlier chapters. The examples import them from package:my_app/adaptive.dart. Replace my_app with your package name and adjust the path to match your project.
Why layouts need tests
Layout bugs seldom show up at the size you develop on. A rail that never appears, a column count that stays at two, or a RenderFlex overflowed error at large text scale all pass a manual check on one phone or one desktop window. Widget tests run in a simulated window, so you can check every breakpoint in seconds and keep checking after later changes.
The test window: physical size, pixel ratio, logical size
In flutter_test, the window starts at 2400 by 1800 physical pixels with a device pixel ratio of 3.0. That gives a logical size of 800 by 600. Widgets, MediaQuery and LayoutBuilder all see logical pixels.
logical size = physicalSize / devicePixelRatioYou change the window through tester.view. Always set the pixel ratio together with the size, so the numbers you write are the logical values your breakpoints use.
import 'package:flutter_test/flutter_test.dart';
import 'package:flutter/widgets.dart';
/// Makes the test window exactly [size] logical pixels.
void setLogicalSize(WidgetTester tester, Size size) {
tester.view.devicePixelRatio = 1.0;
tester.view.physicalSize = size;
addTearDown(tester.view.reset);
}With a ratio of 1.0, physical and logical sizes are equal. addTearDown(tester.view.reset) restores the defaults after the test. Without it, the next test inherits your size and can fail for no obvious reason.
Older code uses tester.binding.window.physicalSizeTestValue. Those members are deprecated. Use tester.view.
A first test: the shell at one size
This is the test from the navigation chapter, rewritten with the helper.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/adaptive.dart';
void setLogicalSize(WidgetTester tester, Size size) {
tester.view.devicePixelRatio = 1.0;
tester.view.physicalSize = size;
addTearDown(tester.view.reset);
}
void main() {
testWidgets('uses a navigation rail on wide windows', (tester) async {
setLogicalSize(tester, const Size(1200, 800));
await tester.pumpWidget(const MaterialApp(home: AdaptiveShell()));
expect(find.byType(NavigationRail), findsOneWidget);
expect(find.byType(NavigationBar), findsNothing);
});
}Set the size before pumpWidget. You can also change it later in the same test, as shown below.
Testing the boundaries
Bugs cluster at the edges of your breakpoints, where < and <= matter. windowSizeFor is a pure function, so test it with plain test and no widgets.
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/adaptive.dart';
void main() {
const cases = [
(0.0, WindowSize.compact),
(599.9, WindowSize.compact),
(600.0, WindowSize.medium),
(839.9, WindowSize.medium),
(840.0, WindowSize.expanded),
(1920.0, WindowSize.expanded),
];
for (final (width, expected) in cases) {
test('windowSizeFor($width) is $expected', () {
expect(windowSizeFor(width), expected);
});
}
}For widgets, run the same idea as a table of window sizes and expected results. Each loop iteration registers its own test, so a failure names the size that broke.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/adaptive.dart';
void main() {
const cases = [
(Size(360, 800), false),
(Size(599, 800), false),
(Size(600, 800), true),
(Size(1200, 800), true),
];
for (final (size, expectRail) in cases) {
testWidgets('rail visible=$expectRail at $size', (tester) async {
tester.view.devicePixelRatio = 1.0;
tester.view.physicalSize = size;
addTearDown(tester.view.reset);
await tester.pumpWidget(const MaterialApp(home: AdaptiveShell()));
expect(
find.byType(NavigationRail),
expectRail ? findsOneWidget : findsNothing,
);
expect(
find.byType(NavigationBar),
expectRail ? findsNothing : findsOneWidget,
);
});
}
}The 599 and 600 rows pin the breakpoint used by AdaptiveShell. If someone changes >= 600 to > 600, the 600 case fails.
Testing local constraints with LayoutBuilder
LayoutBuilder reacts to the constraints of its parent, not to the window. Test that difference directly by putting a widget in a narrow box inside a wide window.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/adaptive.dart';
void main() {
testWidgets('AdaptiveBody follows its parent, not the window',
(tester) async {
tester.view.devicePixelRatio = 1.0;
tester.view.physicalSize = const Size(1200, 800);
addTearDown(tester.view.reset);
await tester.pumpWidget(
const MaterialApp(
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: SizedBox(width: 500, child: AdaptiveBody()),
),
),
),
);
expect(find.text('One pane'), findsOneWidget);
expect(find.text('Two panes, wide'), findsNothing);
});
}The window is 1200 wide, which is an expanded size, but the widget receives 500 pixels and picks the compact layout. A version based on MediaQuery.sizeOf would fail this test. That makes it a good check that you used the right tool.
Testing a resize while the app runs
Real windows resize, and foldables change size when opened. Change tester.view.physicalSize after the first pump, then call pump again so the framework rebuilds.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/adaptive.dart';
void main() {
testWidgets('keeps the selected tab when the window shrinks',
(tester) async {
tester.view.devicePixelRatio = 1.0;
tester.view.physicalSize = const Size(1200, 800);
addTearDown(tester.view.reset);
await tester.pumpWidget(const MaterialApp(home: AdaptiveShell()));
await tester.tap(find.text('Search'));
await tester.pump();
tester.view.physicalSize = const Size(400, 800);
await tester.pump();
expect(find.byType(NavigationRail), findsNothing);
final bar = tester.widget<NavigationBar>(find.byType(NavigationBar));
expect(bar.selectedIndex, 1);
});
}This test passes because _index lives in the shell's State, above the part of the tree that switches. If you moved the index into the rail or bar, it would reset on every switch. This is the kind of regression a single-size test cannot catch.
Text scale and overflow
Layouts also break when users enlarge text. You can simulate this through the platform dispatcher.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:my_app/adaptive.dart';
void main() {
testWidgets('compact shell survives 2x text scale', (tester) async {
tester.view.devicePixelRatio = 1.0;
tester.view.physicalSize = const Size(360, 640);
tester.platformDispatcher.textScaleFactorTestValue = 2.0;
addTearDown(tester.view.reset);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
await tester.pumpWidget(const MaterialApp(home: AdaptiveShell()));
expect(tester.takeException(), isNull);
});
}Overflow errors are reported through FlutterError, and the test framework fails the test on its own. takeException makes the check explicit and fails with the exception text if a layout overflowed.
Golden tests
A golden test compares a rendered widget to a stored image.
await expectLater(
find.byType(AdaptiveShell),
matchesGoldenFile('goldens/shell_expanded.png'),
);Generate or update the files with flutter test --update-goldens. Goldens catch visual regressions that finders cannot, such as spacing or alignment. They have costs, though.
- Fonts and text rendering differ across operating systems, so a golden made on macOS can fail on Linux CI. Generate goldens on the same platform CI uses.
- Every intentional design change requires reviewing and committing new images.
- Use them for a few key screens at one size per window class, not for every state.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Wide test shows the compact layout | Pixel ratio left at 3.0 | Set `devicePixelRatio = 1.0` with the size |
| Later tests fail at odd sizes | Missing `addTearDown(tester.view.reset)` | Reset in every test that changes the view |
| Resize has no visible effect | No `pump` after changing the size | Call `await tester.pump()` |
| Widget test ignores window size | Widget uses `LayoutBuilder` inside a fixed box | Constrain the test parent, as above |
| `find.text('Home')` finds two widgets | Rail label and page body both contain the text | Use `find.byType`, or `descendant` finders |
Exercise
A test sets tester.view.physicalSize = const Size(900, 700) and does not touch devicePixelRatio. The test environment default ratio is 3.0. Which window-size class does the widget see, and what one-line change makes the test see an expanded window?
Show answer
The logical size is 900 / 3 = 300 by about 233, so the widget sees a compact window. Adding tester.view.devicePixelRatio = 1.0 makes the logical width 900, which is at least 840 and therefore expanded.
Exercise
Write the assertions for a test that places AdaptiveBody inside SizedBox(width: 700) in a 1400-pixel-wide window, and say what they should check.
Show answer
With 700 logical pixels of parent width, windowSizeFor returns medium, so the test should call expect(find.text('Two panes, narrow'), findsOneWidget) and expect(find.text('One pane'), findsNothing). The 1400-pixel window is irrelevant because LayoutBuilder reads its parent's constraints.