Flutter futurebuilder refresh

Flutter FutureBuilder Refresh

In Flutter, the FutureBuilder widget is commonly used for asynchronously fetching and displaying data. It allows us to easily handle the state of a future and update the UI accordingly.

To implement a refresh functionality with FutureBuilder, you can follow these steps:

  1. Create a RefreshIndicator widget as the parent of the FutureBuilder widget.
  2. Implement an onRefresh function to handle the refresh action.
  3. Inside the onRefresh function, update the state of the future and trigger a rebuild of the FutureBuilder.

Example:

  
  import 'package:flutter/material.dart';

  class ExamplePage extends StatelessWidget {
    Future<List<String>> fetchData() async {
      // Simulate async fetching of data
      await Future.delayed(Duration(seconds: 2));
      return ["Data 1", "Data 2", "Data 3"];
    }

    Future<void> refreshData(BuildContext context, Function setState) async {
      final List<String> refreshedData = await fetchData();
      setState(() {
        // Update the state and trigger a rebuild
        data = refreshedData;
      });
    }

    List<String> data;

    @override
    Widget build(BuildContext context) {
      return MaterialApp(
        home: Scaffold(
          appBar: AppBar(
            title: Text("Example Page"),
          ),
          body: RefreshIndicator(
            onRefresh: () => refreshData(context, setState),
            child: FutureBuilder<List<String>>(
              future: fetchData(),
              builder: (BuildContext context, AsyncSnapshot<List<String>> snapshot) {
                if (snapshot.connectionState == ConnectionState.waiting) {
                  return Center(child: CircularProgressIndicator());
                } else if (snapshot.hasError) {
                  return Center(child: Text("Error: \${snapshot.error}"));
                } else {
                  return ListView.builder(
                    itemCount: snapshot.data.length,
                    itemBuilder: (BuildContext context, int index) {
                      return ListTile(
                        title: Text(snapshot.data[index]),
                      );
                    },
                  );
                }
              },
            ),
          ),
        ),
      );
    }
  }
  
  

In the above example, we have a ExamplePage that contains a FutureBuilder widget wrapped in a RefreshIndicator. The fetchData function simulates an asynchronous data fetch operation.

The refreshData function is triggered when the user performs a refresh action. It calls the fetchData function again to retrieve the updated data and updates the state of the future using setState. This will trigger a rebuild of the FutureBuilder, updating the UI with the refreshed data.

Inside the build method, we check the ConnectionState of the snapshot to determine the appropriate UI to display. If the connection state is waiting, we show a loading indicator. If there is an error, we display an error message. Otherwise, we display the fetched data using a ListView.builder.

Note that the example code is just a simplified representation. You can customize and expand it based on your specific use case.

Leave a comment