Sub topic 14
Adapting layout to screen size and input, not only platform
The earlier chapters adapted widgets to the platform: Cupertino on iOS, Material elsewhere. This chapter covers a second question. Is the platform a good predictor of how much room you have, or of how the user points at things? Usually it is not.
This chapter assumes you know LayoutBuilder and MediaQuery at a basic level, can write a StatefulWidget, and have read the earlier chapters on detecting the platform and writing adaptive widgets.
Platform, size and input are separate axes
An iPhone and an iPad are both iOS. A Pixel phone and a Pixel Tablet are both Android. A desktop window can be dragged from 400 to 1600 logical pixels wide while the platform stays TargetPlatform.macOS. Android apps can also run in split-screen or on a foldable that changes shape mid-session.
So an app has three independent inputs to its layout decisions:
| Axis | Question it answers | Typical source |
|---|---|---|
| Platform | Which look and behavior conventions apply? | `Theme.of(context).platform` |
| Size | How much space does this part of the UI have? | `LayoutBuilder`, `MediaQuery.sizeOf` |
| Input | Touch, mouse, keyboard, stylus? | Pointer events, `MouseRegion`, focus |
Mixing these up causes common bugs. Checking platform == TargetPlatform.iOS to pick a "phone layout" gives iPad users a stretched phone screen. Checking platform == TargetPlatform.android to enable hover effects gives nothing to Chromebook users and useless code to everyone else.
Measuring size: MediaQuery or LayoutBuilder
Flutter gives you two ways to read size, and they answer different questions.
| Tool | Reports | Use when |
|---|---|---|
| `MediaQuery.sizeOf(context)` | Size of the whole window | You decide app-level structure, such as navigation |
| `LayoutBuilder` | Constraints from the parent | A reusable widget must fit wherever it is placed |
MediaQuery.sizeOf subscribes only to size changes. The older MediaQuery.of(context).size also rebuilds your widget when unrelated values change, such as the keyboard insets, so prefer the specific accessors (sizeOf, orientationOf, textScalerOf).
For most decisions LayoutBuilder is the safer choice. A card inside a 300-pixel side panel on a 1400-pixel window should use its compact layout, and only the parent's constraints tell it that.
Window size classes
Choose breakpoints by width, not by device name. Material 3 uses three classes, and they work well for Cupertino-styled apps too:
| Class | Width in logical pixels | Typical navigation |
|---|---|---|
| Compact | below 600 | Bottom bar |
| Medium | 600 to 839 | Navigation rail |
| Expanded | 840 and above | Extended rail or sidebar |
Put the thresholds in one function so the whole app agrees on them.
import 'package:flutter/material.dart';
enum WindowSize { compact, medium, expanded }
WindowSize windowSizeFor(double width) {
if (width < 600) return WindowSize.compact;
if (width < 840) return WindowSize.medium;
return WindowSize.expanded;
}A navigation shell that follows the available width
This shell swaps a bottom NavigationBar for a NavigationRail when there is room. The destination list and the selected index are shared, so switching layouts mid-session (by rotating, resizing or splitting the screen) keeps the user on the same page.
import 'package:flutter/material.dart';
enum WindowSize { compact, medium, expanded }
WindowSize windowSizeFor(double width) {
if (width < 600) return WindowSize.compact;
if (width < 840) return WindowSize.medium;
return WindowSize.expanded;
}
void main() => runApp(const MaterialApp(home: AdaptiveShell()));
class _Dest {
const _Dest(this.icon, this.label);
final IconData icon;
final String label;
}
const _destinations = [
_Dest(Icons.home, 'Home'),
_Dest(Icons.search, 'Search'),
_Dest(Icons.settings, 'Settings'),
];
class AdaptiveShell extends StatefulWidget {
const AdaptiveShell({super.key});
@override
State<AdaptiveShell> createState() => _AdaptiveShellState();
}
class _AdaptiveShellState extends State<AdaptiveShell> {
int _index = 0;
@override
Widget build(BuildContext context) {
final content = Center(child: Text(_destinations[_index].label));
return LayoutBuilder(
builder: (context, constraints) {
final size = windowSizeFor(constraints.maxWidth);
if (size == WindowSize.compact) {
return Scaffold(
body: content,
bottomNavigationBar: NavigationBar(
selectedIndex: _index,
onDestinationSelected: (i) => setState(() => _index = i),
destinations: [
for (final d in _destinations)
NavigationDestination(icon: Icon(d.icon), label: d.label),
],
),
);
}
return Scaffold(
body: Row(
children: [
NavigationRail(
extended: size == WindowSize.expanded,
selectedIndex: _index,
onDestinationSelected: (i) => setState(() => _index = i),
destinations: [
for (final d in _destinations)
NavigationRailDestination(
icon: Icon(d.icon),
label: Text(d.label),
),
],
),
const VerticalDivider(width: 1),
Expanded(child: content),
],
),
);
},
);
}
}State lives in _AdaptiveShellState, above the LayoutBuilder. If you put _index inside one of the branches, it would reset whenever the width crossed a breakpoint.
The same idea applies on iOS. On a phone, CupertinoTabScaffold with a bottom tab bar is the convention. On a wide iPad window, many apps use a sidebar list and a detail pane. You can build that with a Row and CupertinoListSection in the wide branch and the tab scaffold in the compact branch.
Adapting to input
Touch is the default assumption, but desktop and web builds add a mouse and a keyboard, and tablets may add both. Three practical rules follow.
- Hover is optional polish. Touch devices never produce hover events, so a hover effect must never carry information the user needs.
- Everything reachable by tap must be reachable by keyboard. Use widgets that take focus (
InkWell, buttons,Focus) and do not build interactive controls from a bareGestureDetector. - Pointer cursors are a hint. Show a click cursor over clickable regions on mouse platforms. It is ignored on touch screens.
MouseRegion handles the hover and cursor parts:
import 'package:flutter/material.dart';
class HoverCard extends StatefulWidget {
const HoverCard({super.key, required this.onTap, required this.child});
final VoidCallback onTap;
final Widget child;
@override
State<HoverCard> createState() => _HoverCardState();
}
class _HoverCardState extends State<HoverCard> {
bool _hovering = false;
@override
Widget build(BuildContext context) {
return MouseRegion(
cursor: SystemMouseCursors.click,
onEnter: (_) => setState(() => _hovering = true),
onExit: (_) => setState(() => _hovering = false),
child: Card(
elevation: _hovering ? 6 : 1,
child: InkWell(
onTap: widget.onTap,
child: Padding(
padding: const EdgeInsets.all(16),
child: widget.child,
),
),
),
);
}
}The InkWell supplies tap handling, keyboard focus and Enter or Space activation. The MouseRegion only adds the extra desktop feedback. On a phone, the card still works and the hover state is simply never set.
Tap target size is another input concern. Touch targets should stay around 44 to 48 logical pixels. Material buttons already follow this on touch platforms, and VisualDensity can shrink them on desktop. If you build custom controls, keep the hit area large even when the visible icon is small.
Text scale and unusual sizes
Users can raise the system font size, which makes text take more space inside the same layout. This is a third reason to avoid fixed widths. Prefer Flexible, Expanded, Wrap, and ConstrainedBox with a maxWidth over SizedBox(width: 320). On very wide windows, constrain the content width too. A single column of text 1400 pixels wide is hard to read, so wrap it in Center and a ConstrainedBox(constraints: BoxConstraints(maxWidth: 720)).
Testing layout at different sizes
Widget tests run in a fake window. You can change its size and then assert which branch was built, just as the previous chapter overrode the platform.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'adaptive_shell.dart';
void main() {
testWidgets('compact width uses a bottom bar', (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);
});
testWidgets('wide width uses a rail', (tester) async {
tester.view.physicalSize = const Size(1200, 800);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(const MaterialApp(home: AdaptiveShell()));
expect(find.byType(NavigationRail), findsOneWidget);
expect(find.byType(NavigationBar), findsNothing);
});
}physicalSize is in physical pixels, so setting devicePixelRatio to 1.0 makes the numbers equal logical pixels. addTearDown(tester.view.reset) restores the defaults so one test does not affect the next.
Common mistakes
- Using
dart:ioPlatformfor layout. It does not exist on web and cannot be overridden in tests. Use constraints instead. - Reading
MediaQuerytoo high or too often. Reading the window size inside a small leaf widget ties it to the screen instead of its container. - Storing selection state inside a layout branch. State is lost when the branch changes.
- Assuming a mouse is present on desktop-sized screens. An iPad or Surface can be touch-only at any width.
- Hiding actions behind hover. They become unreachable on touch devices.
Exercise
A teammate writes if (Theme.of(context).platform == TargetPlatform.iOS) return PhoneLayout(); to pick the layout. Name two situations where this gives the wrong result, and say what you would read instead.
Show answer
On an iPad (also iOS) the user gets a stretched phone layout, and on a macOS or Android window resized to a narrow width the user gets the wide layout when a compact one is needed. Read the available width with LayoutBuilder (or MediaQuery.sizeOf for app-level structure) and map it to a window size class such as compact, medium or expanded. Keep the platform check only for choosing Material or Cupertino styling.
Exercise
Why should _index in the navigation shell be stored in the State object above the LayoutBuilder rather than inside the bottom-bar branch?
Show answer
The LayoutBuilder returns a different widget tree when the width crosses a breakpoint, and state stored inside one branch is discarded when that branch is replaced. State held in the parent State object survives, so the user stays on the same destination after rotating, resizing or entering split-screen.