Sub topic 10
One-pane and two-pane list-detail layouts
A list-detail layout shows a collection of items (a list) and the content of one chosen item (the detail). Mail clients, settings screens and file browsers all use it. On a narrow window, the list and the detail take turns on screen. On a wide window, both appear side by side.
This chapter assumes you can read Dart 3 switch expressions and build widget trees with StatefulWidget, Row and Scaffold. It also assumes you know the window-size classes from the breakpoints chapter. The helper windowSizeFor is repeated here so the example runs on its own.
What changes between one pane and two panes
The data and the interaction are the same in both modes. The user picks an item and sees its detail. Only the arrangement changes:
| Mode | Window class | What is on screen | Back button |
|---|---|---|---|
| One pane | compact | List, or detail after a selection | Returns from detail to list |
| Two panes | medium and expanded | List and detail together | Not needed for this navigation |
The most important design decision is where the selection lives. If each layout owns its own state, the user loses their place when the window is resized or rotated. Keep the selected item in one place above the code that chooses the layout. Both layouts then read the same value.
A complete example
The screen below keeps _selectedId in a State object and uses LayoutBuilder to read the width it actually receives. Selecting an item only changes that one value. The layout code decides what the value means.
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;
}
class Message {
const Message(this.id, this.title, this.body);
final int id;
final String title;
final String body;
}
final messages = List.generate(
20,
(i) => Message(i, 'Message $i', 'Body of message $i.'),
);
void main() => runApp(const MaterialApp(home: MailPage()));
class MailPage extends StatefulWidget {
const MailPage({super.key});
@override
State<MailPage> createState() => _MailPageState();
}
class _MailPageState extends State<MailPage> {
int? _selectedId;
void _select(int id) => setState(() => _selectedId = id);
void _clear() => setState(() => _selectedId = null);
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
final twoPane = windowSizeFor(constraints.maxWidth) != WindowSize.compact;
final selected = _selectedId == null
? null
: messages.firstWhere((m) => m.id == _selectedId);
final list = MessageList(selectedId: _selectedId, onSelected: _select);
if (twoPane) {
return Scaffold(
appBar: AppBar(title: const Text('Inbox')),
body: Row(
children: [
SizedBox(width: 320, child: list),
const VerticalDivider(width: 1),
Expanded(
child: selected == null
? const Center(child: Text('Select a message'))
: MessageDetail(key: ValueKey(selected.id), message: selected),
),
],
),
);
}
if (selected == null) {
return Scaffold(
appBar: AppBar(title: const Text('Inbox')),
body: list,
);
}
return PopScope(
canPop: false,
onPopInvokedWithResult: (didPop, result) {
if (!didPop) _clear();
},
child: Scaffold(
appBar: AppBar(
leading: BackButton(onPressed: _clear),
title: Text(selected.title),
),
body: MessageDetail(key: ValueKey(selected.id), message: selected),
),
);
},
);
}
}
class MessageList extends StatelessWidget {
const MessageList({
super.key,
required this.selectedId,
required this.onSelected,
});
final int? selectedId;
final ValueChanged<int> onSelected;
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: messages.length,
itemBuilder: (context, index) {
final m = messages[index];
return ListTile(
title: Text(m.title),
selected: m.id == selectedId,
onTap: () => onSelected(m.id),
);
},
);
}
}
class MessageDetail extends StatelessWidget {
const MessageDetail({super.key, required this.message});
final Message message;
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(message.title, style: Theme.of(context).textTheme.headlineSmall),
const SizedBox(height: 8),
Text(message.body),
],
),
);
}
}How the example works
Selection state survives layout changes
_selectedId belongs to _MailPageState, and LayoutBuilder sits inside build. Resizing the window rebuilds the builder but keeps the State. Suppose a user on a wide window has Message 5 open and then shrinks the window below 600 logical pixels. They land on Message 5's detail view with a back button. If they widen it again, the two-pane view returns with Message 5 still highlighted.
Back handling without a pushed route
The compact detail view is not a pushed route. It is the same screen showing different content. That makes the layout switch safe, but the system back gesture would normally leave the whole page. PopScope with canPop: false intercepts the gesture. When didPop is false, the callback clears the selection, which returns to the list. onPopInvokedWithResult needs Flutter 3.22 or newer. Older versions use onPopInvoked.
When no item is selected in compact mode, there is no PopScope, so back behaves normally and leaves the page.
Why the key on the detail
ValueKey(selected.id) tells Flutter that a different message is a different widget. Here MessageDetail is stateless, so the key changes little. It matters once the detail holds state, such as a scroll position, a text field or a reply draft. Without the key, that state would carry over from one message to the next.
Choosing the breakpoint
The example treats medium and expanded the same way. A 320-pixel list leaves 280 pixels for the detail at the 600-pixel boundary, which is tight but usable. If your detail needs more room, switch to two panes only at the expanded class (840 or more) or give the list a smaller width. The decision belongs in one expression, so it is easy to change.
Edge cases
- No selection in two-pane mode. The detail pane needs an empty state, such as the "Select a message" text. Do not leave it blank, and do not auto-select the first item without thinking. Auto-selecting is reasonable for tablets, but it triggers an unwanted detail load every time a user shrinks and widens the window.
- Selected item removed. If the item is deleted,
firstWherethrows aStateError. In real code, usewhere(...).firstOrNull(fromdart:collectionextensions in Dart 3) and clear the selection when the result is null. - Deep links. The selection should be derivable from a URL or route parameter on the web and on desktop. With a router such as
go_router, the selected id comes from a path parameter instead ofsetState. The layout code stays the same. - Constraints, not the screen.
LayoutBuilderreports the space this widget gets. If the list-detail screen is embedded in a side panel, it chooses its layout from that panel's width, which is usually what you want.
Testing both modes
The test below checks both behaviors. It assumes the example code is in lib/main.dart of a package named list_detail_demo. It uses tester.view to set the window size, as in the testing chapter.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:list_detail_demo/main.dart';
void main() {
testWidgets('compact: detail replaces the list', (tester) async {
tester.view.physicalSize = const Size(400, 800);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(const MaterialApp(home: MailPage()));
await tester.tap(find.text('Message 1'));
await tester.pump();
expect(find.text('Body of message 1.'), findsOneWidget);
expect(find.text('Message 0'), findsNothing);
});
testWidgets('expanded: list and detail share the screen', (tester) async {
tester.view.physicalSize = const Size(1200, 800);
tester.view.devicePixelRatio = 1.0;
addTearDown(tester.view.reset);
await tester.pumpWidget(const MaterialApp(home: MailPage()));
expect(find.text('Select a message'), findsOneWidget);
await tester.tap(find.text('Message 1'));
await tester.pump();
expect(find.text('Body of message 1.'), findsOneWidget);
expect(find.text('Message 0'), findsOneWidget);
});
}A third test is worth writing: select an item at 1200 pixels wide, resize to 400, and assert that the detail is still showing. That test covers the state-preservation guarantee directly.
Exercise
In the example, the user is on a compact window with Message 3's detail open and then rotates the device so the width becomes 900 logical pixels. What do they see, and why? Then name one change you would need if the detail view were pushed with Navigator.push instead.
Show answer
They see the two-pane layout with the list on the left, Message 3 highlighted, and Message 3's detail on the right. The selection lives in _MailPageState, above LayoutBuilder, so it survives the rebuild, and the width of 900 maps to the expanded class, which uses two panes. With Navigator.push, the pushed detail route would stay on the stack and cover the two-pane layout, so you would have to pop the route when the layout becomes two-pane, or move the selection into state as in the example.
Exercise
Why does the compact branch wrap the detail Scaffold in PopScope with canPop: false, and what happens to the system back gesture on the compact list screen?
Show answer
The detail is not a separate route, so the system back gesture would otherwise leave the whole page. PopScope with canPop: false intercepts it, and when didPop is false the callback clears the selection, which returns to the list. On the compact list screen there is no PopScope, so back behaves normally and leaves the page.