How to refresh futurebuilder flutter

Maybe you are looking for a way to refresh the data in a FutureBuilder widget in Flutter. Let me explain the solution in detail with examples.

The FutureBuilder widget allows you to build UI components based on the state of a Future. It takes a Future as input and rebuilds itself whenever the Future completes with new data. However, it does not have a built-in mechanism to refresh the Future or re-fetch the data.

One approach to refresh the FutureBuilder is by using a GlobalKey to access its state and calling the setState() method when you want to trigger a refresh. Here’s an example:

    
import 'package:flutter/material.dart';

class MyWidget extends StatefulWidget {
  const MyWidget({Key key}) : super(key: key);

  @override
  _MyWidgetState createState() => _MyWidgetState();
}

class _MyWidgetState extends State {
  Future fetchData() async {
    // Simulate an async fetch operation
    await Future.delayed(Duration(seconds: 2));
    return 'New Data';
  }

  final GlobalKey _refreshKey = GlobalKey();

  void _refresh() {
    _refreshKey.currentState.show();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My Widget'),
        actions: [
          IconButton(
            icon: Icon(Icons.refresh),
            onPressed: _refresh,
          ),
        ],
      ),
      body: RefreshIndicator(
        key: _refreshKey,
        onRefresh: () async {
          setState(() {}); // Trigger refresh by calling setState
        },
        child: FutureBuilder(
          future: fetchData(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
              );
            } else if (snapshot.hasError) {
              return Center(
                child: Text('Error: ${snapshot.error}'),
              );
            } else {
              return Center(
                child: Text('Data: ${snapshot.data}'),
              );
            }
          },
        ),
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: MyWidget(),
  ));
}
    
  

In this example, we have a StatefulWidget called MyWidget. Inside its state, we have a fetchData() method that simulates an async fetch operation. The _refresh() method is called when the refresh button in the AppBar is pressed. It triggers the refresh by accessing the RefreshIndicatorState through the _refreshKey and calling its show() method.

Inside the build() method, we use the RefreshIndicator widget to wrap the FutureBuilder. The RefreshIndicator’s onRefresh callback is triggered when the user pulls down on the screen. Within this callback, we simply call setState() to rebuild the UI and refresh the FutureBuilder.

Finally, the FutureBuilder handles the different states of the Future. If the Future is still loading, we show a CircularProgressIndicator. If there’s an error, we display an error message. Otherwise, we display the fetched data.

This is just one approach to refresh a FutureBuilder, but there are other alternatives depending on your specific use case. Hopefully, this example helps you in refreshing the data in a FutureBuilder widget in Flutter. Good luck with your project!

Leave a comment