Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 73 ยท Layout

ListView, GridView and Slivers

Build scrolling screens in Flutter: ListView.builder, separated lists, lazy building, GridView, CustomScrollView, SliverAppBar and how a viewport builds only what is visible.

Nearly every app has a list: messages, products, settings, search results. Flutter's scrolling widgets are built to handle lists with thousands (or an unlimited number) of items smoothly, and the trick is laziness: only the items near the screen are ever built. Understanding this explains why ListView.builder is the default choice, why shrinkWrap can hurt performance, and how fancy collapsing headers work.

This lesson covers ListView and its constructors, GridView, and the sliver system behind both (CustomScrollView, SliverAppBar). It relies on the unbounded-constraints idea from Constraints go down, sizes go up, since a scrollable gives its children unbounded space in the scroll direction.

Real vs stand-in. ListView, GridView and the sliver widgets are real Flutter, and the Dart code is read-only. The live examples are JavaScript stand-ins that compute which items a viewport would build for a given scroll offset.

Choose your scrollable

ListView One column of items.
GridView Items in rows and columns.
CustomScrollView Mix lists, grids and headers.
1 / 2

ListView

The simplest form takes a list of children:

DART
ListView(
  padding: const EdgeInsets.all(16),
  children: const [
    ListTile(leading: Icon(Icons.wifi), title: Text('Wi-Fi')),
    ListTile(leading: Icon(Icons.bluetooth), title: Text('Bluetooth')),
    ListTile(leading: Icon(Icons.battery_full), title: Text('Battery')),
  ],
)

This builds every child immediately. That is fine for a settings page of ten rows and a bad idea for a feed of a thousand. For long or unknown-length lists use ListView.builder:

DART
ListView.builder(
  itemCount: messages.length,
  itemBuilder: (context, index) {
    final message = messages[index];
    return ListTile(
      key: ValueKey(message.id),
      title: Text(message.title),
      subtitle: Text(message.preview),
    );
  },
)

itemBuilder is called only for indexes that are about to become visible. Leave out itemCount and the list is infinite: the builder is called with ever larger indexes until it returns null. That is how endless feeds work.

ListView.separated adds a divider (or any widget) between items:

DART
ListView.separated(
  itemCount: items.length,
  itemBuilder: (context, i) => ItemTile(items[i]),
  separatorBuilder: (context, i) => const Divider(height: 1),
)

Useful properties

  • scrollDirection: Axis.horizontal makes a horizontal list. Give a horizontal ListView a fixed height (wrap it in a SizedBox), because the cross axis is unbounded when it sits inside a Column.
  • itemExtent (or prototypeItem) tells the list every row has the same height. It can then skip measuring items and jump to any offset in constant time, which is a real speed-up for long lists.
  • controller: ScrollController() lets you read the scroll position, jump or animate to an offset, or detect that the user reached the end to load more. Always dispose a controller you created in a State (StatefulWidget and setState).
  • physics changes the feel: BouncingScrollPhysics, ClampingScrollPhysics, NeverScrollableScrollPhysics.
  • shrinkWrap: true makes the list as tall as all its children, which forces it to measure every item and defeats laziness. Use it for short lists inside another scroller, never for long ones.
  • cacheExtent is how far beyond the visible area items are pre-built (250 logical pixels by default), so scrolling does not reveal blank space.

When you build many rows, keep per-item widgets small and const where you can, and give items stable keys if they can be reordered or removed, see Keys and widget identity.

How lazy building works

The scroll view is a viewport, a window onto a very long strip. Given the current scroll offset and the window height, it computes which items overlap the window (plus the cache extent), asks the builder for exactly those, and discards items that moved far away. This stand-in does the same arithmetic for equal-height rows and counts how many items it has ever built.

JS A lazy viewport

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Even with a million items, only about 20 tiles are alive at once. With a plain ListView(children: [...]), all one million widgets would exist up front. Note the line jump near the end: because every row has the same height, the viewport finds the range by division, with no need to measure the rows before it. This is the benefit of itemExtent.

GridView

A GridView is a scrollable grid. There are three common ways to build one:

DART
// A fixed number of columns.
GridView.count(
  crossAxisCount: 3,
  mainAxisSpacing: 8,
  crossAxisSpacing: 8,
  padding: const EdgeInsets.all(8),
  children: tiles,
)

// As many columns as fit, each at most 160 px wide.
GridView.extent(maxCrossAxisExtent: 160, children: tiles)

// Lazy grid for many items, with a delegate that describes the columns.
GridView.builder(
  gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
    maxCrossAxisExtent: 180,
    childAspectRatio: 3 / 4,          // width / height of each cell
    mainAxisSpacing: 12,
    crossAxisSpacing: 12,
  ),
  itemCount: products.length,
  itemBuilder: (context, i) => ProductCard(products[i]),
)

SliverGridDelegateWithFixedCrossAxisCount keeps the column count constant, so cells stretch on wide screens. SliverGridDelegateWithMaxCrossAxisExtent keeps the cell width roughly constant and adds columns as the screen gets wider, which makes it the better default for responsive layouts (Responsive and adaptive layouts). Each cell is crossAxisExtent / columns wide and, using childAspectRatio, width / ratio tall.

JS Grid column math

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Slivers: the engine under the hood

ListView and GridView are conveniences. Underneath, a scroll view is a viewport that displays a list of slivers: pieces of scrollable content that each know how to lay out only their visible part. CustomScrollView lets you combine slivers in one scrolling surface, with a single scroll position:

DART
CustomScrollView(
  slivers: [
    const SliverAppBar(
      pinned: true,
      expandedHeight: 200,
      flexibleSpace: FlexibleSpaceBar(title: Text('Gallery')),
    ),
    SliverPadding(
      padding: const EdgeInsets.all(8),
      sliver: SliverGrid.builder(
        gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 140),
        itemCount: photos.length,
        itemBuilder: (context, i) => PhotoTile(photos[i]),
      ),
    ),
    const SliverToBoxAdapter(child: ListTile(title: Text('Recently viewed'))),
    SliverList.builder(
      itemCount: recent.length,
      itemBuilder: (context, i) => ListTile(title: Text(recent[i])),
    ),
  ],
)

Key slivers:

Sliver Purpose
SliverAppBar An app bar that collapses, can pin to the top, float back in when scrolling up, and snap
SliverList / SliverList.builder A lazy list
SliverGrid / SliverGrid.builder A lazy grid
SliverToBoxAdapter Puts one normal widget (like a header) in the sliver list
SliverPadding Adds padding around another sliver
SliverFillRemaining Fills the remaining viewport, useful for an empty state

Everything in slivers must be a sliver. A normal widget like Text has to be wrapped in SliverToBoxAdapter; otherwise you get a "RenderBox was given... sliver" type error. SliverAppBar collapses by watching the scroll offset: its height goes from expandedHeight down to the toolbar height, and FlexibleSpaceBar fades or scales its background and title in between.

The mental model, which the next stand-in mimics, is that the viewport walks through the slivers with a "remaining paint space", and each sliver reports how much scroll extent it consumed.

JS Slivers sharing one scroll position

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Reorderable, dismissible and infinite lists

Three behaviors users expect from a modern list are built from the widgets you already know.

Drag to reorder

ReorderableListView lets the user long-press (or drag a handle) to move an item. Every child needs a unique key, and you must update your data in onReorder:

DART
ReorderableListView.builder(
  itemCount: _tasks.length,
  itemBuilder: (context, i) => ListTile(
    key: ValueKey(_tasks[i].id),          // identity, not the index
    title: Text(_tasks[i].title),
    trailing: ReorderableDragStartListener(index: i, child: const Icon(Icons.drag_handle)),
  ),
  onReorder: (oldIndex, newIndex) {
    setState(() {
      if (newIndex > oldIndex) newIndex -= 1;   // the index is counted before removal
      final item = _tasks.removeAt(oldIndex);
      _tasks.insert(newIndex, item);
    });
  },
)

The newIndex -= 1 line is the classic gotcha: when an item moves down, newIndex is its position in the list that still contains the dragged item. Set buildDefaultDragHandles: false when you provide your own handle as above. Keys follow the rules in Keys and widget identity.

Swipe actions

Dismissible (covered in Gestures and input handling) removes an item with a swipe. For actions that reveal buttons behind the row, such as "Archive" and "Delete" like a mail app, the flutter_slidable package provides Slidable with an ActionPane:

DART
Slidable(
  key: ValueKey(item.id),
  endActionPane: ActionPane(
    motion: const DrawerMotion(),
    children: [
      SlidableAction(onPressed: (_) => _archive(item), icon: Icons.archive, label: 'Archive'),
      SlidableAction(onPressed: (_) => _delete(item), icon: Icons.delete, label: 'Delete', backgroundColor: Colors.red),
    ],
  ),
  child: ListTile(title: Text(item.title)),
)

Always offer another path to the same action (a menu or a detail screen), because swipe gestures are hard to discover and difficult for some users (accessibility).

Horizontal lists and infinite scroll

A horizontal list inside a vertical screen needs a fixed height, since the cross axis is unbounded:

DART
SizedBox(
  height: 140,
  child: ListView.separated(
    scrollDirection: Axis.horizontal,
    padding: const EdgeInsets.symmetric(horizontal: 16),
    itemCount: cards.length,
    separatorBuilder: (_, __) => const SizedBox(width: 12),
    itemBuilder: (_, i) => SizedBox(width: 200, child: CardTile(cards[i])),
  ),
)

For infinite scroll, load the next page when the user nears the end. A ScrollController listener checks the position, and flags prevent duplicate requests:

DART
final _controller = ScrollController();
bool _loading = false;
bool _hasMore = true;

@override
void initState() {
  super.initState();
  _controller.addListener(() {
    final nearEnd = _controller.position.pixels >= _controller.position.maxScrollExtent - 300;
    if (nearEnd) _loadMore();
  });
}

Future<void> _loadMore() async {
  if (_loading || !_hasMore) return;
  setState(() => _loading = true);
  final page = await repository.fetchPage(_nextPage);
  setState(() {
    _items.addAll(page.items);
    _nextPage += 1;
    _hasMore = page.hasMore;
    _loading = false;
  });
}

Show a spinner as the last item while _loading is true, and wrap the list in RefreshIndicator(onRefresh: ...) for pull-to-refresh. Dispose the controller.

JS Pagination guard: no duplicate loads

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Common mistakes

  • A ListView inside a Column without Expanded causes "Vertical viewport was given unbounded height". Wrap it in Expanded (Row, Column, Expanded and Flexible).
  • Column inside SingleChildScrollView for hundreds of rows builds all rows. Use ListView.builder.
  • Nested scrollables with the same direction fight over gestures. Prefer one CustomScrollView with slivers.
  • Creating expensive objects in itemBuilder: it runs often while scrolling. Keep it cheap and fetch data elsewhere.
  • Using index as identity when items can be reordered: give widgets keys from your data's ids.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is ListView.builder better than ListView(children: [...]) for 10,000 items?

    itemBuilder is called only for items that are about to be visible; the plain constructor builds every child up front.
  2. 2. What does shrinkWrap: true do to a long ListView?

    To know its total size the list must lay out all children, so laziness is lost.
  3. 3. Which grid delegate adds more columns on wider screens while keeping cell width similar?

    MaxCrossAxisExtent computes the column count from the available width and the maximum cell width.
  4. 4. You want a normal Text header inside CustomScrollView. How do you add it?

    The slivers list only accepts sliver widgets; SliverToBoxAdapter wraps one ordinary box widget.
  5. 5. What does pinned: true do on a SliverAppBar?

    A pinned SliverAppBar shrinks to its toolbar height and stays visible; without pinned it scrolls away.

Summary

  • Scrollables are lazy: only items near the viewport are built, so use ListView.builder and GridView.builder for long data.
  • ListView.separated, itemExtent, cacheExtent, controllers and physics tune behavior; shrinkWrap breaks laziness.
  • GridView is configured by a delegate: fixed column count or maximum cell width.
  • CustomScrollView mixes slivers (SliverAppBar, SliverList, SliverGrid, SliverToBoxAdapter) in one scroll position.
  • Scrollables give unbounded space in their direction: size them with Expanded or SizedBox.

Next: Responsive and Adaptive Layouts