Menu
CoddyTech

Pull to Refresh

Part of the Data and the Network section of Coddy's Flutter journey. Lesson 9 of 27.

On a phone, people pull a list down to reload it. A spinner drops in from the top, and the data updates. Flutter's widget for it is RefreshIndicator:

RefreshIndicator(
  onRefresh: refresh,
  child: ListView(
    children: [ ... ],
  ),
)

onRefresh is a function that returns a Future. The pull spinner stays until that future is done, so await the new data inside it:

Future<void> refresh() async {
  setState(() {
    _tip = fetch('/tip');
  });
  await _tip;
}

The pull only works on something that scrolls. Put the content in a ListView, even when it is a single item: a ListView can always be pulled. The pull spinner already says the app is working, so the builder can keep the old tip with a hasData check.

challenge icon

Challenge

Medium

Make the tip reload when you pull the screen down:

  • add a refresh method that sets a new _tip in setState and awaits it
  • wrap the body in a RefreshIndicator with onRefresh: refresh
  • put the FutureBuilder in a ListView inside it

In the preview, drag the screen down with the mouse.

Try it yourself

import 'package:flutter/material.dart';

import 'api.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: TipScreen(),
    );
  }
}

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

  @override
  State<TipScreen> createState() => _TipScreenState();
}

class _TipScreenState extends State<TipScreen> {
  late Future<String> _tip;

  @override
  void initState() {
    super.initState();
    _tip = fetch('/tip');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Tip of the Day'),
      ),
      body: Center(
        child: Padding(
          padding: const EdgeInsets.all(24),
          child: FutureBuilder<String>(
              future: _tip,
              builder: (context, snapshot) {
                if (snapshot.hasData) {
                  return Text(
                    snapshot.data!,
                    textAlign: TextAlign.center,
                    style: const TextStyle(fontSize: 24),
                  );
                }
                return const CircularProgressIndicator();
              },
            ),
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and the Network

Practice on your own: Online Flutter compiler