Sub topic 16
Mixing lists and grids with CustomScrollView and slivers
ListView and GridView each scroll one kind of content. Real screens often need more: a collapsing app bar, a short list of featured items, then a grid of products, all moving as one scroll. This chapter shows how CustomScrollView and slivers do that.
This chapter assumes you can use ListView.builder and GridView.builder, and that you know what a grid delegate is. It also assumes you know why a scrollable needs bounded height inside a Column.
What a sliver is
A sliver is a piece of a scrollable area. Ordinary widgets such as Card or Text are laid out as boxes with a width and a height. A sliver is laid out by a different protocol, which receives the scroll offset and the visible region. It reports how much scroll extent it occupies and how much of that is currently painted.
ListView and GridView are conveniences built on this. Each one creates a scroll view with a single sliver inside it. CustomScrollView takes the same machinery and lets you supply the list of slivers yourself.
All slivers share one scroll position. Each sliver builds only the children that fall inside the visible region plus a small cache area. Lazy building therefore works across the whole combined view.
A list and a grid in one scroll view
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: ShopPage()));
class ShopPage extends StatelessWidget {
const ShopPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
const SliverAppBar(title: Text('Shop'), floating: true),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) => ListTile(title: Text('Featured $index')),
childCount: 3,
),
),
SliverGrid(
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
),
delegate: SliverChildBuilderDelegate(
(context, index) =>
Card(child: Center(child: Text('Product $index'))),
childCount: 20,
),
),
],
),
);
}
}Compare this with the builder constructors you already know:
SliverListtakes adelegate, whereListView.buildertakesitemBuilderanditemCount.SliverGridtakes both agridDelegateand adelegate. The grid delegate decides the column layout, as inGridView.builder. The child delegate supplies the tiles.SliverChildBuilderDelegateis the lazy delegate.SliverChildListDelegatetakes an explicit list of widgets and suits short, fixed content.
Always pass childCount when the number of items is finite. Without it, the builder is asked for indexes forever unless it returns null to stop. A builder that always returns a widget makes an endless list.
Recent Flutter versions also provide shorter constructors such as SliverList.builder, SliverGrid.count and SliverGrid.builder. They wrap the delegates above. Check that your Flutter version has them before relying on them.
Common sliver building blocks
| Sliver | Purpose |
|---|---|
| `SliverAppBar` | App bar that can float, snap, pin or collapse as you scroll |
| `SliverList` | Linear list of items, lazily built |
| `SliverGrid` | Grid of items, lazily built |
| `SliverToBoxAdapter` | Wraps one ordinary widget so it can sit among slivers |
| `SliverPadding` | Adds padding around a sliver |
| `SliverFillRemaining` | Fills the space left when the content is shorter than the viewport |
Putting ordinary widgets between slivers
The slivers list accepts only slivers. If you put a Text, Padding or Container in it, Flutter throws an error saying a RenderViewport expected a child of type RenderSliver. Wrap box widgets in SliverToBoxAdapter. Use SliverPadding where you would use Padding around a sliver.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: CatalogPage()));
class CatalogPage extends StatelessWidget {
const CatalogPage({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: CustomScrollView(
slivers: [
SliverAppBar(
pinned: true,
expandedHeight: 160,
flexibleSpace: const FlexibleSpaceBar(title: Text('Catalog')),
),
const SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.all(16),
child: Text(
'Popular items',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
),
SliverPadding(
padding: const EdgeInsets.symmetric(horizontal: 8),
sliver: SliverGrid(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 160,
mainAxisSpacing: 8,
crossAxisSpacing: 8,
),
delegate: SliverChildBuilderDelegate(
(context, index) =>
Card(child: Center(child: Text('Tile $index'))),
childCount: 30,
),
),
),
const SliverFillRemaining(
hasScrollBody: false,
child: Center(child: Text('End of catalog')),
),
],
),
);
}
}Points to notice:
SliverPaddingtakes the wrapped sliver in itssliverparameter, notchild.SliverAppBarwithpinned: truestays at the top once collapsed.floating: truemakes it reappear as soon as the user scrolls back up.snap: true(only valid withfloating) completes the reveal automatically.expandedHeightwithFlexibleSpaceBargives the collapsing header effect.hasScrollBody: falseonSliverFillRemainingtells it the child is not scrollable. The child is then sized to fit and centered in the remaining space. With the defaulttrue, the child must be able to handle a bounded viewport on its own.
Behavior to expect
Scroll direction. CustomScrollView has scrollDirection, reverse, physics and controller, with the same meaning as on ListView. Every sliver in one view uses the same axis. A horizontal view needs slivers whose main axis is horizontal, which SliverList and SliverGrid handle automatically.
Controllers and infinite scroll. Pass a ScrollController to CustomScrollView and read position.extentAfter as you did with a single list. The position covers all slivers together, so a load-more check at the end applies to the whole page.
Pull to refresh. RefreshIndicator works around a CustomScrollView. If the first sliver is not scrollable content, make sure the view still can overscroll. Setting physics: const AlwaysScrollableScrollPhysics() ensures the gesture works on short content.
State and keys. Items built by sliver delegates are created and destroyed as they scroll in and out of the visible area. Item state is lost unless you use keys or AutomaticKeepAliveClientMixin. This is the same rule as for ListView.builder.
Common mistakes
- A
ListViewinside aCustomScrollView. A box widget in thesliverslist triggers theRenderSlivererror. If you wrap it inSliverToBoxAdapter, it gets an unbounded height, which brings back the unbounded-height error. UseSliverListinstead. shrinkWrap: trueto combine scrollables. AListViewwithshrinkWrap: truenested in another scroll view builds all its items at once. You lose lazy building. Slivers avoid this and keep the whole view lazy.- Missing
childCount. The list never ends if the builder always returns a widget. - Using
Paddinginstead ofSliverPadding.Paddingcannot wrap a sliver, so it causes the same type error. - Several
SliverAppBars pinned together. Pinned bars stack on top of each other and use up screen space. Pin only one. - A tall
SliverToBoxAdapterchild. It is built completely, even if only a small part is visible. Put long repeating content in aSliverListso it builds lazily.
Choosing between the options
- Use
ListVieworGridViewwhen the screen has exactly one list or one grid. They are shorter and easier to read. - Use
CustomScrollViewwhen the same scroll must contain more than one kind of content, or when you need a collapsing app bar or sticky headers. - Use
SliverToBoxAdapterfor a small header, banner or button between sections. Avoid it for large content.
Exercise
A screen needs a pinned app bar, a text heading reading "Recent", a lazily built list of 50 rows, and a grid of 40 tiles that adapts its column count to screen width. Which slivers and delegates would you put in a CustomScrollView, and in what order?
Show answer
Use SliverAppBar(pinned: true), then SliverToBoxAdapter wrapping the heading Text, then SliverList with a SliverChildBuilderDelegate and childCount: 50, then SliverGrid with SliverGridDelegateWithMaxCrossAxisExtent as the gridDelegate and a SliverChildBuilderDelegate with childCount: 40. Use SliverPadding if you need padding around the list or grid.
Exercise
Why does a ListView with shrinkWrap: true placed inside a SliverToBoxAdapter hurt performance on a list of 5000 items, and what is the fix?
Show answer
With shrinkWrap the list must measure all of its children to compute its height, so it builds all 5000 items at once and loses lazy building. The fix is to use a SliverList with a SliverChildBuilderDelegate directly in the slivers list, so only the visible items are built.