Sub topic 12
Collapsing app bars with SliverAppBar
This chapter assumes you know Scaffold, AppBar, and MaterialApp from the earlier chapters. It also assumes you can read a StatelessWidget and use ListView.builder. You will replace the fixed AppBar with a bar that scrolls with the content, shrinks, and returns when the user scrolls back.
Why a normal AppBar cannot collapse
Scaffold.appBar places the bar in a fixed slot above the body. The scaffold gives the bar a fixed height and never moves it. The body scrolls underneath, so the bar cannot react to the scroll position.
A collapsing bar must be part of the scrollable content. Flutter does this with slivers. A sliver is a piece of a scrollable area that knows how to lay itself out and respond to the scroll offset. A ListView is a convenience wrapper that builds a single list sliver for you. CustomScrollView lets you list the slivers yourself and mix different kinds in one scroll.
SliverAppBar is the app bar written as a sliver. It sits first in the slivers list of a CustomScrollView. It then shrinks, hides, or reappears as the scroll offset changes.
The smallest working example
This is a complete app. Run it as shown.
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Sliver demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
useMaterial3: true,
),
home: const FeedPage(),
);
}
}
class FeedPage extends StatelessWidget {
const FeedPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
const SliverAppBar(
title: Text('Feed'),
floating: true,
),
SliverList.builder(
itemCount: 30,
itemBuilder: (context, index) =>
ListTile(title: Text('Item $index')),
),
],
),
);
}
}Three things changed compared with the earlier screens:
- The
Scaffoldhas noappBar. The bar lives insidebody. - The body is a
CustomScrollView, and itssliverslist holds the bar and the list. floating: truemakes the bar reappear as soon as the user scrolls up, even from far down the list.
The scaffold still provides the overall screen structure: background color, drawer, floating action button, and ScaffoldMessenger access. Only the bar's position changed.
The four scroll behaviors
The scrolling behavior comes from a few boolean properties. Each one answers a separate question.
| Property | Question it answers | Effect when true |
|---|---|---|
| `pinned` | Does the collapsed bar stay on screen? | The bar shrinks to its normal height and stays at the top. |
| `floating` | Does the bar return on any upward scroll? | The bar reappears as soon as the user scrolls up, without reaching the list start. |
| `snap` | Does the bar finish its motion by itself? | After a partial reveal or hide, the bar animates fully open or closed. It requires `floating: true`. |
| `stretch` | Does overscroll enlarge the bar? | Pulling past the top stretches the flexible space (use with `stretchModes`). |
The defaults are all false. With every flag off, the bar scrolls away with the content and returns only when the user reaches the very top of the list.
Common combinations:
pinned: truealone gives a bar that collapses to a standard height and stays visible. This is the usual choice for a large header image.floating: truegives the quick-return bar from the example above.floating: true, snap: truegives the same bar, but it never rests half-visible.pinned: true, floating: truekeeps the collapsed bar visible and also lets the expanded area return on upward scrolls.
Adding an expandable header
To get a tall header that shrinks, set expandedHeight and give the bar a flexibleSpace. The usual flexibleSpace is a FlexibleSpaceBar, which scales and fades its background and moves its title as the bar collapses.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: ProfilePage()));
class ProfilePage extends StatelessWidget {
const ProfilePage({super.key});
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
return Scaffold(
body: CustomScrollView(
slivers: [
SliverAppBar(
pinned: true,
expandedHeight: 200,
actions: [
IconButton(
icon: const Icon(Icons.share),
tooltip: 'Share',
onPressed: () {},
),
],
flexibleSpace: FlexibleSpaceBar(
title: const Text('Profile'),
background: DecoratedBox(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [scheme.primary, scheme.primaryContainer],
),
),
),
),
),
SliverList.builder(
itemCount: 40,
itemBuilder: (context, index) =>
ListTile(title: Text('Entry $index')),
),
],
),
);
}
}Note where the title goes. When you use FlexibleSpaceBar, give the title to the FlexibleSpaceBar, not to SliverAppBar.title. The flexible space title animates its size and position. If you set both, you will see two titles.
expandedHeight is the height when fully open. The collapsed height is the normal toolbar height (toolbarHeight, 56 by default) plus the status bar padding. If expandedHeight is smaller than that, the bar will not collapse in any visible way.
Material 3 sizes
Material 3 defines medium and large top bars that collapse into a standard one. Flutter provides named constructors for them:
SliverAppBar.large(
title: const Text('Library'),
)SliverAppBar.medium works the same way with a shorter expanded height. Both use the theme's text styles for the expanded and collapsed title. They are the simplest option when you want the collapsing look without a background image. They need useMaterial3: true, which is the default in current Flutter versions.
What stays automatic
SliverAppBar behaves like AppBar in the ways you already know:
- Back button. If the route can be popped, the bar shows a back button. This is controlled by
automaticallyImplyLeading. - Drawer icon. If the enclosing
Scaffoldhas adrawerand the route cannot be popped, the bar shows a menu icon that opens the drawer. This works becauseSliverAppBaris below the scaffold in the widget tree. - Actions and leading.
actions,leading, andtitlework as onAppBar. - Theme colors. The bar takes its colors from
AppBarThemeand theColorScheme.
So you can move from AppBar to SliverAppBar and keep your navigation behavior intact.
Mixing other slivers
A CustomScrollView accepts only slivers. To place an ordinary widget in the scroll, wrap it. The table lists the common slivers.
| Sliver | Use |
|---|---|
| `SliverList.builder` | A lazily built list of items. |
| `SliverGrid.builder` | A lazily built grid. It needs a `gridDelegate`. |
| `SliverToBoxAdapter` | Holds one ordinary widget, such as a heading or a banner. |
| `SliverPadding` | Adds padding around another sliver. |
| `SliverFillRemaining` | Fills the space left in the viewport, useful for empty states. |
Example of a heading between the bar and the list:
CustomScrollView(
slivers: [
const SliverAppBar.medium(title: Text('Inbox')),
const SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.all(16),
child: Text('Recent messages'),
),
),
SliverList.builder(
itemCount: 20,
itemBuilder: (context, index) =>
ListTile(title: Text('Message $index')),
),
],
)Because the list is built lazily, only the visible items are created, as in ListView.builder.
Common errors
Putting SliverAppBar in Scaffold.appBar. The appBar slot expects a PreferredSizeWidget. SliverAppBar is not one, so the code fails with a type error at compile time. Put it in a CustomScrollView inside body.
Putting a normal widget in slivers. A Text, Container, or Padding in the list throws a runtime error such as "A RenderBox was given to a RenderSliver." Wrap it in SliverToBoxAdapter, or use the matching sliver such as SliverPadding.
Using snap without floating. Flutter asserts that snap needs floating: true. Set both.
Nesting a ListView inside a CustomScrollView. A ListView in a SliverToBoxAdapter has unbounded height inside the scroll and fails to lay out. Use SliverList instead, so there is one scrollable.
Two titles. Setting title on both the SliverAppBar and its FlexibleSpaceBar draws both.
Content hidden under the status bar. A SliverAppBar handles the top safe area itself. Do not wrap the whole CustomScrollView in SafeArea with the top inset, or the bar gets an extra gap. If you have no bar, add SafeArea or SliverSafeArea yourself.
A TabBar that scrolls away. If you need tabs under a bar that collapses, use SliverAppBar.bottom for the TabBar. For tabs that each have their own scrolling list, you will need a NestedScrollView. That is a separate topic, and it is not required for the patterns in this chapter.
Choosing between AppBar and SliverAppBar
Use a plain AppBar when the bar is always visible and the content is a simple screen or form. It is simpler, and the scaffold manages the layout. Use SliverAppBar when the bar should collapse or hide to give content more room, or when the header is large and decorative. The cost is that the body must be a CustomScrollView built from slivers. Screens that are not scrollable, such as a login form, do not benefit.
A mixed app is common: most screens use AppBar, and one or two feed or profile screens use SliverAppBar. Because both sit under the same Scaffold and MaterialApp, the theme, routes, and drawer work the same way for both.
Exercise
A teammate writes Scaffold(appBar: SliverAppBar(title: Text('Feed')), body: ListView(...)) and the app does not compile. Explain why, and show how to restructure it so the bar hides when the user scrolls down and returns as soon as they scroll up.
Show answer
Scaffold.appBar requires a PreferredSizeWidget, and SliverAppBar is a sliver, not one. A sliver must be a child of a scroll view that lays out slivers. Remove the appBar argument and make the body a CustomScrollView whose first sliver is SliverAppBar(title: Text('Feed'), floating: true). Replace the ListView with a sliver such as SliverList.builder(itemCount: ..., itemBuilder: ...). Add snap: true if the bar should always finish opening or closing instead of stopping half-visible.
Exercise
You set pinned: true and expandedHeight: 48 on a SliverAppBar with a FlexibleSpaceBar, but the bar never appears to collapse. What is the likely cause, and what do you change?
Show answer
The collapsed height is the toolbar height (56 by default) plus the status bar inset, so expandedHeight: 48 is already smaller than the collapsed size and there is nothing to shrink. Increase expandedHeight to a value larger than that, for example 200, so the bar has room to collapse down to the pinned height.