Sub topic 13
Putting it together: a composed screen layout
This chapter combines the tools from earlier chapters into one screen. It assumes you can read Row, Column, Expanded, SizedBox, Padding, Stack, and Positioned. It also assumes you know the rule that constraints go down and sizes go up. The aim is a repeatable method for building a screen, not a new widget.
A method for composing layouts
Large layouts go wrong when you try to write them all at once. Work from the outside in:
- Split the screen into horizontal bands and decide which one absorbs spare height. Usually one band scrolls or stretches and the others are fixed.
- Pick the outer widget for each band. Use
Columnfor stacked bands,Rowfor side-by-side items, andStackonly when children truly overlap. - Decide for each child whether it takes its natural size, a fixed size, or a share of the leftover space.
- Pull each band into its own widget class, so each class has one layout job.
The screen below is a trip summary. It has a banner with overlapping text and a badge, a row of three statistics, a scrolling activity list, and a bottom action bar.
The full screen
Put this in lib/main.dart of a new project. It runs as shown.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: TripScreen()));
class TripScreen extends StatelessWidget {
const TripScreen({super.key});
@override
Widget build(BuildContext context) {
return const Scaffold(
body: SafeArea(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
HeaderBanner(),
StatsRow(),
Expanded(child: ActivityList()),
ActionBar(),
],
),
),
);
}
}
class HeaderBanner extends StatelessWidget {
const HeaderBanner({super.key});
@override
Widget build(BuildContext context) {
return const SizedBox(
height: 200,
child: Stack(
children: [
Positioned.fill(
child: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [Colors.teal, Colors.indigo],
),
),
),
),
Positioned(
top: 12,
right: 12,
child: Chip(
avatar: Icon(Icons.star, size: 18),
label: Text('Top rated'),
),
),
Positioned(
left: 16,
right: 16,
bottom: 16,
child: Text(
'Lisbon in three days',
style: TextStyle(
color: Colors.white,
fontSize: 26,
fontWeight: FontWeight.bold,
),
),
),
],
),
);
}
}
class StatsRow extends StatelessWidget {
const StatsRow({super.key});
@override
Widget build(BuildContext context) {
return const Padding(
padding: EdgeInsets.all(16),
child: Row(
children: [
Expanded(child: Stat(icon: Icons.schedule, label: '3 days')),
Expanded(child: Stat(icon: Icons.euro, label: '420')),
Expanded(child: Stat(icon: Icons.star, label: '4.8')),
],
),
);
}
}
class Stat extends StatelessWidget {
const Stat({super.key, required this.icon, required this.label});
final IconData icon;
final String label;
@override
Widget build(BuildContext context) {
return Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon),
const SizedBox(height: 4),
Text(label, overflow: TextOverflow.ellipsis),
],
);
}
}
class ActivityList extends StatelessWidget {
const ActivityList({super.key});
@override
Widget build(BuildContext context) {
return ListView(
children: const [
ListTile(leading: Icon(Icons.museum), title: Text('Gulbenkian Museum')),
ListTile(leading: Icon(Icons.train), title: Text('Tram 28 ride')),
ListTile(leading: Icon(Icons.restaurant), title: Text('Pastel de nata tour')),
ListTile(leading: Icon(Icons.castle), title: Text('Sao Jorge Castle')),
ListTile(leading: Icon(Icons.beach_access), title: Text('Day trip to Cascais')),
ListTile(leading: Icon(Icons.music_note), title: Text('Fado evening')),
ListTile(leading: Icon(Icons.park), title: Text('Eduardo VII Park')),
ListTile(leading: Icon(Icons.shopping_bag), title: Text('LX Factory')),
],
);
}
}
class ActionBar extends StatelessWidget {
const ActionBar({super.key});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Expanded(
child: OutlinedButton(
onPressed: () {},
child: const Text('Save'),
),
),
const SizedBox(width: 12),
Expanded(
flex: 2,
child: FilledButton(
onPressed: () {},
child: const Text('Book now'),
),
),
],
),
);
}
}Reading the layout band by band
The outer Column
The Column runs with the default MainAxisSize.max, so it fills the height SafeArea gives it. CrossAxisAlignment.stretch forces each child to the full screen width. That is why the banner needs no explicit width and the action bar buttons have room to split.
Three children have fixed heights. They are the banner (200 logical pixels), the stats row, and the action bar. Their heights come from content and padding. The Expanded around the list takes whatever height remains. The Column gives the ListView a bounded height through that Expanded. Without it, the ListView would receive unbounded height and throw an error.
The banner Stack
The SizedBox supplies a bounded height and, because of stretch, a tight width. The Stack then sizes itself to those constraints. All three children are positioned:
Positioned.fillstretches the gradient to the full banner.- The badge is pinned to the top-right with two offsets.
- The title uses
leftandrighttogether, which fixes its width. It is then pinned atbottom. A long title wraps inside that width instead of overflowing.
Later children paint over earlier ones, so the order is background, badge, title. Reversing the first two would hide the gradient's neighbors behind it.
The stats Row
Each Stat sits in an Expanded, so the three columns share the width equally. Without Expanded, they would cluster at the left and you would need MainAxisAlignment.spaceAround to spread them. Expanded is the better choice here because each stat now has a known maximum width. The inner Column uses MainAxisSize.min so it is only as tall as its icon and text. The Row centers it vertically by default.
The action bar
The two buttons are Expanded with flex values of 1 and 2 (the default flex is 1). The SizedBox(width: 12) is a fixed gap. Flex only divides what remains after fixed-size children are measured, so the gap does not shrink the ratio.
Which widget does which job
| Need | Widget | Why |
|---|---|---|
| Stack bands vertically | `Column` | Main axis is vertical |
| Absorb leftover height | `Expanded` | Gives children a bounded share |
| Equal-width columns | `Row` of `Expanded` | Each child gets a tight width |
| Overlap text on a background | `Stack` with `Positioned` | Children share one box |
| Fixed gap | `SizedBox` | No layout side effects |
| Edge inset for a group | `Padding` | Insets the whole subtree |
| Bound a `Stack` or `ListView` | `SizedBox` or `Expanded` | Supplies finite constraints |
Common failures when composing
Each failure below comes from a rule you already know, applied to a larger tree.
- A
Stackcollapses or misbehaves in aColumn. AStackwith only positioned children has no natural size and takes the largest size its constraints allow. In aColumnthat means infinite height. Wrap it in aSizedBoxorAspectRatio, as the banner does. Expandedoutside aRoworColumn.Expandedis parent data for a flex widget. Putting aPaddingbetween theRowand theExpandedcauses a "Incorrect use of ParentDataWidget" error. KeepExpandedas a direct child.Positionedoutside aStack. The same rule applies. ThePositionedmust be a direct child of theStack.- Overflow when the keyboard opens. If you add a
TextFieldto this screen, the keyboard shrinks the available height and the fixed bands may no longer fit. Make the middle band scrollable, or wrap the content in aSingleChildScrollViewand drop theExpanded. - Text that outgrows its slot. Long stat labels overflow a narrow
Expandedunless you setoverflowor allow wrapping. The stat widget uses an ellipsis for this reason.
Extracting widgets for maintainability
The screen is split into classes (HeaderBanner, StatsRow, ActivityList, ActionBar) instead of helper methods. Each class has a const constructor, so Flutter can skip rebuilding it when its parent rebuilds with the same arguments. Each class also keeps its layout decisions in one place. If a designer asks for the badge on the left, you change one Positioned and nothing else.
Keep the layout contract visible at the top of each class. A reader should see how the widget expects to be sized: whether it needs a bounded height, whether it expects to be inside a Row, and whether it stretches. When you cannot tell from the widget alone, add a short comment.
Exercise
In the trip screen, you want the activity list to scroll, but you remove the Expanded around ActivityList to "simplify" the tree. What happens, and which two changes would fix it while keeping the list scrollable between the stats and the action bar?
Show answer
The Column passes unbounded height to the ListView, so Flutter reports a "Vertical viewport was given unbounded height" error and the screen fails to lay out. The fix is to restore Expanded around ActivityList, which gives the list the leftover height. An alternative is to wrap the list in a SizedBox with a fixed height, but that does not adapt to different screen sizes. Setting shrinkWrap: true on the list silences the error but is a poor choice for long lists.
Exercise
You add a small "Free cancellation" label that must sit over the bottom-left corner of the banner, 16 pixels from the left and 48 pixels above the bottom edge. Which widget do you add, where do you put it, and which properties do you set?
Show answer
Add a Positioned widget as a direct child of the banner's Stack, with left: 16 and bottom: 48, and place the label widget (for example a Text or Chip) inside it. Put it after the gradient in the children list so it paints on top. Setting top as well would stretch it vertically, so leave top unset.