To implement pull-to-refresh functionality in Flutter, the RefreshIndicator widget is commonly used. This widget wraps a scrollable widget, such as ListView or ScrollView, and displays a loading indicator while triggering an asynchronous operation to load data when the user pulls down.
Here is a specific example demonstrating how to implement pull-to-refresh in a simple ListView:
dartimport 'package:flutter/material.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { List<String> items = List.generate(20, (i) => "Item $i"); Future<void> refreshList() async { await Future.delayed(Duration(seconds: 2)); // Simulates the waiting time for a network request setState(() { items.addAll(List.generate(20, (i) => "New item $i")); }); } Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Pull-to-Refresh Example'), ), body: RefreshIndicator( onRefresh: refreshList, child: ListView.builder( itemCount: items.length, itemBuilder: (context, index) { return ListTile( title: Text(items[index]), ); }, ), ), ); } }
In this example, we create a basic ListView where each list item is a simple text widget. The onRefresh property of RefreshIndicator is a function that returns a Future, defining the behavior of the refresh operation. In our example, this function simulates a network request using Future.delayed and then updates the list data.
Using RefreshIndicator not only enhances user experience but also keeps the page data updated, making it a commonly used feature in mobile development.