DEV Community

Cover image for pull_refresh: pull-to-refresh and load-more for any Flutter scroll view
Abdeldjalil Chougui
Abdeldjalil Chougui

Posted on Originally published at abdeldjalilchougui.biz

pull_refresh: pull-to-refresh and load-more for any Flutter scroll view

Almost every list in a mobile app needs the same two gestures: pull down to refresh, and reach the end to load the next page. Flutter's RefreshIndicator covers the first one in the Material style. For both together, with custom headers and footers, the common choice has been pull_to_refresh and its SmartRefresher widget.

That works until the edge cases show up. The README of pull_refresh lists the ones it set out to fix, with their upstream issue numbers: a controller called after its widget is gone crashes, a header that does not collapse after a failed refresh, load-more that fires repeatedly or never on a short list, and a CustomScrollView with a SliverAppBar that crashes.

pull_refresh is a clean-room replacement for pull_to_refresh. The API is close enough that migrating mostly means renaming one widget.

What it does

Works with the scroll views you already have. ListView, GridView and CustomScrollView with any slivers, including SliverAppBar. With a simpler footer, it also works with SingleChildScrollView and NestedScrollView.

Works with any ScrollPhysics. The physics are detected on each gesture:

  • Bouncing (iOS, macOS): the header appears in the overscroll gap, and the content is held below it while refreshing.
  • Clamping (Android and others): the header is an overlay that follows your finger and floats over the content.

Load-more that behaves. It starts automatically near the end, with a configurable footerTriggerDistance. Short lists, where the content is shorter than the viewport, can still be pulled, and load-more fires once per pull-up gesture and never loops. Refresh and load-more never run at the same time. Load-more has a "no more data" state, and a failed load shows a retry button.

Built-in indicators. ClassicHeader (arrow, text, last-update time), MaterialHeader (a Material 3 spinner), WaterDropHeader and ClassicFooter. You can build your own with CustomHeader, whose builder receives the mode and the drag offset, or CustomFooter.

Localisation and RTL. Strings for English, French and Arabic are bundled, and you can add any language through a LocalizationsDelegate. Every indicator lays out right-to-left in RTL locales.

Accessibility. There is a "Refresh" custom semantics action, spoken announcements for "refreshing" and for the result, and a labelled retry button.

A controller you cannot crash. The controller is safe to use after the widget is gone and after dispose(): calls do nothing and never throw.

How to use it

Add it from GitHub:

dependencies:
  pull_refresh:
    git: https://github.com/AbdeldjalilChougui/pull_refresh
Enter fullscreen mode Exit fullscreen mode

Wrap your list in PullRefresh and drive it with a RefreshController:

import 'package:flutter/material.dart';
import 'package:pull_refresh/pull_refresh.dart';

class FeedPage extends StatefulWidget {
  const FeedPage({super.key});

  @override
  State<FeedPage> createState() => _FeedPageState();
}

class _FeedPageState extends State<FeedPage> {
  final _controller = RefreshController();
  final _items = List.generate(20, (i) => 'Item $i');

  Future<void> _onRefresh() async {
    try {
      await Future<void>.delayed(const Duration(seconds: 1)); // fetch page 1
      setState(() => _items
        ..clear()
        ..addAll(List.generate(20, (i) => 'Item $i')));
      _controller.refreshCompleted(resetFooterState: true);
    } catch (_) {
      _controller.refreshFailed();
    }
  }

  Future<void> _onLoading() async {
    try {
      await Future<void>.delayed(const Duration(seconds: 1)); // fetch next page
      final next = List.generate(20, (i) => 'Item ${_items.length + i}');
      setState(() => _items.addAll(next));
      if (_items.length >= 100) {
        _controller.loadNoData();
      } else {
        _controller.loadComplete();
      }
    } catch (_) {
      _controller.loadFailed();
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PullRefresh(
      controller: _controller,
      enablePullUp: true,
      header: const ClassicHeader(showLastUpdated: true),
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: ListView.builder(
        itemCount: _items.length,
        itemBuilder: (context, i) => ListTile(title: Text(_items[i])),
      ),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

The controller tells the widget how each operation ended. refreshCompleted() shows "completed" and collapses the header. refreshFailed() shows "failed" and collapses the header so the user can pull again. loadComplete() returns the footer to idle, loadNoData() switches it to "no more data" and stops load-more, and loadFailed() turns it into a retry button. requestRefresh() and requestLoading() start an operation from code; their future resolves to false if it is not possible.

A custom header is a builder:

PullRefresh(
  controller: controller,
  header: CustomHeader(
    height: 72,
    builder: (context, mode, offset) => Center(
      child: mode == RefreshStatus.refreshing
          ? const CircularProgressIndicator()
          : Transform.rotate(
              angle: offset / 40,
              child: const Icon(Icons.autorenew),
            ),
    ),
  ),
  child: ListView(children: const []),
);
Enter fullscreen mode Exit fullscreen mode

Two layout notes from the README. With clamping physics the header floats over the content, so when the content starts with a pinned SliverAppBar, pass edgeOffset: kToolbarHeight + MediaQuery.paddingOf(context).top to keep the header below the bar. With a NestedScrollView, pass notificationPredicate: (n) => n.depth <= 1 so the inner list drives the widget as well.

Migrating from pull_to_refresh

The short version of the README's migration guide:

  1. Replace the dependency and the import.
  2. Rename SmartRefresher to PullRefresh. The parameters controller, onRefresh, onLoading, enablePullDown, enablePullUp, header, footer and child keep their names and meaning.
  3. The RefreshController methods keep their names.
  4. MaterialClassicHeader becomes MaterialHeader, and CustomHeader's builder now also receives the drag offset.
  5. The RefreshConfiguration settings move to PullRefresh parameters.
  6. LoadStatus.canLoading is gone, because loading starts automatically near the end.

Some behaviour changes on purpose, and each change has a regression test: one controller on two widgets no longer throws (the most recently attached widget wins), calls after the widget is gone are ignored, the header always collapses after refreshFailed(), and load-more fires once per gesture on short lists.

Not ported: two-level refresh, the Bezier and Link indicators, horizontal and reversed lists, RefreshConfiguration inheritance, and vibration.

Things to know

  • Vertical scrolling only. Horizontal and reverse: true scroll views are passed through unchanged, with no header and no footer. Chat-style reversed lists are not supported.
  • Your ScrollView is rebuilt. A ListView, GridView or CustomScrollView child is rebuilt as a CustomScrollView with the same slivers and settings plus a footer sliver. So find.byType(ListView) finds nothing in widget tests; use find.byType(Scrollable) or find.byType(CustomScrollView). A ScrollView subclass that overrides build or buildViewport loses that override.
  • Physics are wrapped in AlwaysScrollableScrollPhysics so short content can be pulled. NeverScrollableScrollPhysics is left alone.
  • Children that are not ScrollViews get their footer drawn over the bottom edge once scrolled to the end, not as part of the content.
  • Bouncing physics. The header stays pinned at the top while refreshing, even if the user scrolls the list.
  • Widget tests. A loading footer that is built but offscreen keeps its spinner ticking, so use pump(duration) instead of pumpAndSettle() while loading.
  • Flutter versions. Tested with Flutter 3.35.6. The declared minimum is Flutter 3.24, but it has not been compiled against 3.24.

Why I built it

Pull-to-refresh with load-more is one of those features every list screen needs and nobody wants to debug. The failures the README lists are the kind that only show up in real use: a network call that returns after the user left the screen, a first page with three items, an app bar pinned at the top.

I wanted a widget that keeps the API people already know from pull_to_refresh, so moving to it is a rename, while fixing those cases and covering each one with a regression test. I also wanted Arabic and RTL to work without extra setup, and screen readers to get a real "Refresh" action instead of a gesture they cannot perform.

Get the code

The source, the migration guide and a runnable example app with three tabs (ListView, Material header with simulated failures, and slivers with a SliverAppBar) are on GitHub: https://github.com/AbdeldjalilChougui/pull_refresh. It's MIT licensed. Issues and pull requests are welcome.


Originally published at abdeldjalilchougui.biz.

Top comments (0)