Sub topic 13
Pull to refresh
Pull to refresh lets a user drag a list down past its top edge to reload its data. Flutter provides this through the RefreshIndicator widget. This chapter covers how it works, how to wire it to a list, and the errors that stop it from appearing. It assumes you can write a StatefulWidget, use async and await in Dart, and build a ListView as covered in earlier chapters.
What RefreshIndicator does
RefreshIndicator wraps a scrollable widget. It listens to the scroll notifications that the scrollable sends. When the user drags past the start of the content far enough, it shows a circular spinner and calls your onRefresh callback.
The callback has the type Future<void> Function(). The spinner stays on screen until the returned Future completes, then it animates away. You do not control the spinner directly. You control it by returning a Future that finishes when your data has been reloaded.
The sequence looks like this:
A complete example
The following app shows a list of fake messages. Each pull replaces the list with a new batch. It runs as shown.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: RefreshDemo()));
class RefreshDemo extends StatefulWidget {
const RefreshDemo({super.key});
@override
State<RefreshDemo> createState() => _RefreshDemoState();
}
class _RefreshDemoState extends State<RefreshDemo> {
int _loads = 1;
List<String> _items = _makeItems(1);
static List<String> _makeItems(int load) {
return List<String>.generate(20, (i) => 'Message ${i + 1} (load $load)');
}
Future<List<String>> _fetch(int load) async {
await Future<void>.delayed(const Duration(seconds: 1));
return _makeItems(load);
}
Future<void> _refresh() async {
try {
final next = _loads + 1;
final fresh = await _fetch(next);
if (!mounted) return;
setState(() {
_loads = next;
_items = fresh;
});
} catch (error) {
if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Could not refresh')),
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Inbox')),
body: RefreshIndicator(
onRefresh: _refresh,
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) {
return ListTile(
leading: const Icon(Icons.mail),
title: Text(_items[index]),
);
},
),
),
);
}
}Three details in this code matter.
_refreshisasyncand awaits the fetch. If it returned before the fetch finished, the spinner would vanish too early.- The
mountedcheck runs after theawait. The user may have left the screen during the delay. CallingsetStateon a disposedStatethrows an error. - The error is caught inside
_refresh. An exception that escapes does not crash the indicator, but the user sees nothing. A snack bar tells them the refresh failed.
Which scrollable it works with
RefreshIndicator works with any scrollable that sends scroll notifications. This includes ListView, GridView, CustomScrollView and SingleChildScrollView. By default it reacts to the first scrollable below it in the widget tree. The child does not have to be the scrollable itself, but a scrollable must sit directly beneath it with no other scrollable in between.
With a CustomScrollView, place the RefreshIndicator around the whole view, not around individual slivers. Slivers are not scrollables, so wrapping one of them has no effect.
When the list is too short to scroll
The most common problem is that the gesture does nothing. On Android, the default scroll physics are ClampingScrollPhysics. If the content fits on screen, the list cannot scroll, so it never reports an overscroll, and the indicator never fires.
The fix is to set physics to AlwaysScrollableScrollPhysics, which lets the list respond to drags even when the content is shorter than the viewport.
RefreshIndicator(
onRefresh: _refresh,
child: ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: const [
ListTile(title: Text('Only one row')),
],
),
)An empty state has the same problem. A list with zero items has no scrollable extent, so the user cannot pull to retry. Use a CustomScrollView with SliverFillRemaining to show a message that fills the screen while the view remains scrollable:
RefreshIndicator(
onRefresh: _refresh,
child: const CustomScrollView(
physics: AlwaysScrollableScrollPhysics(),
slivers: [
SliverFillRemaining(
hasScrollBody: false,
child: Center(child: Text('Nothing here. Pull down to retry.')),
),
],
),
)Configuring the indicator
RefreshIndicator has several properties that change how it looks and when it triggers.
| Property | Effect |
|---|---|
| `color` | Color of the spinner arc. |
| `backgroundColor` | Color of the circle behind the spinner. |
| `displacement` | Distance from the top edge to the spinner, in logical pixels. The default is 40. |
| `edgeOffset` | Moves the point where the spinner starts to appear. Use it when the list sits below a header that overlaps it. |
| `strokeWidth` | Thickness of the spinner arc. |
| `triggerMode` | `RefreshIndicatorTriggerMode.onEdge` starts a refresh only when the drag begins at the scroll edge. `anywhere` also allows it after scrolling back to the top in the same gesture. |
| `notificationPredicate` | Chooses which scroll notifications to react to. |
The constructor RefreshIndicator.adaptive draws a Material spinner on Android and a Cupertino-style spinner on iOS and macOS. Use it when you want a native look on each platform without writing platform checks.
Starting a refresh from code
Sometimes the data should reload without a gesture. An example is a "Refresh" button, or a first load when the screen opens. Give the indicator a GlobalKey<RefreshIndicatorState> and call show(). This plays the spinner animation and runs onRefresh.
final GlobalKey<RefreshIndicatorState> _refreshKey =
GlobalKey<RefreshIndicatorState>();
// In build:
RefreshIndicator(
key: _refreshKey,
onRefresh: _refresh,
child: ListView.builder(
itemCount: _items.length,
itemBuilder: (context, index) => ListTile(title: Text(_items[index])),
),
)
// Elsewhere, for example in a button's onPressed:
_refreshKey.currentState?.show();show() returns a Future that completes when the refresh is done. currentState is null until the widget has been built, so use the ?. operator.
Nested scrollables
A horizontal list inside a vertical list is a nested scrollable. By default the indicator listens to notifications at depth 0, the nearest scrollable below it. If the vertical list is not the nearest one, the indicator may react to the wrong scrollable or to none. Pass a notificationPredicate that tests the depth you want:
RefreshIndicator(
onRefresh: _refresh,
notificationPredicate: (ScrollNotification n) => n.depth == 1,
child: PageView(
children: [
ListView(children: const [ListTile(title: Text('Page one'))]),
],
),
)Here the PageView is depth 0 and the inner ListView is depth 1, so the pull gesture on the inner list triggers the refresh.
Cupertino style in slivers
For an iOS-style refresh that sits inside the scroll content, Flutter provides CupertinoSliverRefreshControl. It is a sliver, so it goes at the start of a CustomScrollView's slivers list. It also takes an onRefresh that returns a Future. It needs import 'package:flutter/cupertino.dart'; and bouncing physics to work, which iOS provides by default.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Pulling does nothing on a short list | Content fits the viewport, so no overscroll happens | Set `AlwaysScrollableScrollPhysics` |
| Spinner disappears instantly | `onRefresh` did not return the `Future`, or it returned before the work finished | Mark it `async` and `await` the work, or `return` the future |
| Spinner never disappears | The `Future` never completes, for example a request with no timeout | Add a timeout and handle the error |
| "setState() called after dispose()" | The screen closed during the `await` | Check `mounted` before `setState` |
| Pull works on the wrong list | Several scrollables nested | Set `notificationPredicate` |
| Wrapped slivers do nothing | `RefreshIndicator` was placed around a sliver | Wrap the whole `CustomScrollView` |
Design notes
Replace the list data instead of appending to it. A refresh means "show me the current state", and appending would create duplicates.
If your list also loads more items near the end, as in the infinite scroll chapter, reset the paging state when you refresh. Otherwise the page counter keeps pointing at the old position.
Keep the old data visible while the request runs. Do not clear the list at the start of _refresh, because the user would see an empty screen under the spinner.
Exercise
A screen shows a ListView with three items inside a RefreshIndicator. On a phone, pulling down does nothing. The onRefresh callback is correct. What is the cause and the fix?
Show answer
Three items fit on the screen, so the list is not scrollable and never reports an overscroll, which means the indicator is never triggered. Set physics: const AlwaysScrollableScrollPhysics() on the ListView.
Exercise
Why does the example _refresh method check mounted after the await, and what happens if you remove the check and the user leaves the screen during the request?
Show answer
The await suspends the method, and the State may be disposed before it resumes. Calling setState on a disposed State throws an error. Checking if (!mounted) return; after the await avoids the call.
Exercise
Write the line that starts a refresh programmatically, given a GlobalKey<RefreshIndicatorState> named _refreshKey that is attached to the indicator.
Show answer
_refreshKey.currentState?.show();