RefreshIndicator

  • Code

    The RefreshIndicator widget in Flutter provides a standard way to add the "swipe to refresh" functionality to a scrollable widget, typically a ListView, GridView, or CustomScrollView. It's commonly used when you want users to pull down on the screen to trigger a refresh action.

    
    import 'package:flutter/material.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          home: MyRefreshIndicator(),
        );
      }
    }
    
    class MyRefreshIndicator extends StatefulWidget {
      @override
      _MyRefreshIndicatorState createState() => _MyRefreshIndicatorState();
    }
    
    class _MyRefreshIndicatorState extends State<MyRefreshIndicator> {
      List<String> items = List.generate(20, (index) => 'Item ${index + 1}');
      GlobalKey<RefreshIndicatorState> refreshKey = GlobalKey<RefreshIndicatorState>();
    
      Future<void> refreshList() async {
        // Simulating data fetching delay with Future.delayed
        await Future.delayed(Duration(seconds: 2));
    
        // Add new items or update the list here
        setState(() {
          items = List.generate(20, (index) => 'Refreshed Item ${index + 1}');
        });
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text('RefreshIndicator Example')),
          body: RefreshIndicator(
            key: refreshKey,
            onRefresh: refreshList,
            child: ListView.builder(
              itemCount: items.length,
              itemBuilder: (BuildContext context, int index) {
                return ListTile(
                  title: Text(items[index]),
                  // Add onTap or other interactions as needed
                );
              },
            ),
          ),
        );
      }
    }
    
    
    
    

    In this example, a RefreshIndicator wraps a ListView.builder. The onRefresh callback is called when the user performs the swipe-down action to refresh the list. In this case, the refreshList function simulates the refresh by replacing the existing list items with new ones after a delay.