Reload data when using FutureBuilder

Viewed 56232

I am loading data when widget is loading like the code below. Once the UI is fully loaded, I like to add one refresh button to reload the data again.

How can I refresh the view ?

  class _MyHomePageState extends State<MyHomePage> {

      @override
      Widget build(BuildContext context) {
        var futureBuilder = new FutureBuilder(
          future: _getData(),
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
              case ConnectionState.waiting:
                return new Text('loading...');
              default:
                if (snapshot.hasError)
                  return new Text('Error: ${snapshot.error}');
                else
                  return createListView(context, snapshot);
            }
          },
        );

        return new Scaffold(
          appBar: new AppBar(
            title: new Text("Home Page"),
          ),
          body: futureBuilder,
        );
      }

      Future<List<String>> _getData() async {
        var values = new List<String>();

        await new Future.delayed(new Duration(seconds: 5));

        return values;
      }

      Widget createListView(BuildContext context, AsyncSnapshot snapshot) {

      }
    }
5 Answers
Widget createListView(BuildContext context, AsyncSnapshot snapshot) {
  RaisedButton button = RaisedButton(
    onPressed: () {
      setState(() {});
    },
    child: Text('Refresh'),
  );
  //.. here create widget with snapshot data and with necessary button
}

I did a deep dive into this and it's not that difficult. The builder is properly rebuilt on changing the future (if you trigger the change with setState). Problem is, the hasData and hasError aren't reset until the response is back. But we can use connectionState instead.

final builder = FutureBuilder(
    future: _future,
    builder: (context, snapshot) {
      if (snapshot.connectionState != ConnectionState.done) {
        return _buildLoader();
      }
      if (snapshot.hasError) {
        return _buildError();
      }
      if (snapshot.hasData) {
        return _buildDataView();
      }     
      return _buildNoData();
});

Here's a post on the issue and a linked repo showing the issue and solution: https://www.greycastle.se/reloading-future-with-flutter-futurebuilder/

what i did an it worked for me, is to call the future function again in setState(). in your example it will looks like this.

first you assign your _getData() future function to a variable (_myData) with the same return type, after that, you can override it's value in setState() that will rebuild the UI and therefor run the future again.

in code it will looks like this.(from you example):

class _MyHomePageState extends State<MyHomePage> {

Future<List<String>>  _myData = _getData(); //<== (1) here is your Future

@override
      Widget build(BuildContext context) {
        var futureBuilder = new FutureBuilder(
          future: _myData; //<== (2) here you provide the variable (as a future)
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            switch (snapshot.connectionState) {
              case ConnectionState.none:
              case ConnectionState.waiting:
                return new Text('loading...');
              default:
                if (snapshot.hasError)
                  return Column(
                  children: [
                    Icon(Icons.error),
                    Text('Failed to fetch data.'),
                    RaisedButton(
                      child: Text('RETRY'), 
                      onPressed: (){
                        setState(){
                            _myData = _getData(); //<== (3) that will trigger the UI to rebuild an run the Future again
                        }
                      },
                    ),
                  ],
                );
                else
                  return createListView(context, snapshot);
            }
          },
        );

        return new Scaffold(
          appBar: new AppBar(
            title: new Text("Home Page"),
          ),
          body: futureBuilder,
        );
      }

You can refresh widget by clicking on FlatButton. The code is below.

class _MyHomePageState extends State<MyHomePage> {

  String display;

  Widget futureBuilder() {

 return new FutureBuilder<String>(builder: (context, snapshot) {
 // if(snapshot.hasData){return new Text(display);}    //does not display updated text
 if (display != null) {
  return new Text(display);
  // return your createListView(context, snapshot);

  }
  return new Text("no data yet");
  });
}

  @override
  Widget build(BuildContext context) {

    return new Scaffold(
      appBar: new AppBar(
        title: new Text("Home Page"),
      ),
      body: Center(
             child: Column(
                 mainAxisAlignment: MainAxisAlignment.center,
                 children: <Widget>[
                        FlatButton(onPressed: () async{
                            result = await _getData();
                            print(result);
                                // Result will be your json response

                            setState(() {
                                display = result; //assign any string value from result to display variable.
                            });
                        },
                        child: new Text("Get Data")
                        ),
                        futureBuilder()
                ],
            ),
        ),

    );
  }

  Future<List<String>> _getData() async {
    var values = new List<String>();

    await new Future.delayed(new Duration(seconds: 5));

    return values;
  }

  Widget createListView(BuildContext context, AsyncSnapshot snapshot) {

  }
}

The FutureBuilder will refresh if a variable is included in the query and setState is invoked with that variable.

Because my query has no needed variables I ran into this problem. To solve this, I created a local dummy variable and then incremented it in setState to cause a refresh.

int _dummy = 0;

Then in set state I did this

              setState(() {
                _dummy++;
              });

The dummy is passed into the query even though it is not used.

            child: FutureBuilder<List<InterviewDetails>>(
                future: dbService.getInterviewDetails(_dummy),

Lastly, I needed to make it wait for the view to close by putting "await"

          ElevatedButton(
            child: const Text('Sign In'),
            onPressed: () async {
              await Navigator.push(
                context,
                MaterialPageRoute(builder: (context) => SignInView()),
              );
              setState(() {
                _dummy++;
              });
            },
          ),

In review:

  • The "sign in" button lets the person sign in.
  • The future builder list needs to show that person who is signed in.
  • wait for the view to close by await and increment the dummy in set state
  • have the future builder use a dummy variable in the query
  • ignore the dummy in the query
Related