flutterflutter-futurebuilderrebuild

Refresh FutureBuilder after snapshot.hasError | Flutter


i want to rebuild my FutureBuilder after if's builder leads to snapshot.hasError

I tried using Statefullbuilder to rebuild my FutureBuilder by making and changing random bool, is it a way to resolve problem? I really can't find out until problem comes out

bool boolin = false;
 StatefulBuilder(
    builder: (context, setState) => FutureBuilder(
      initialData: '',
      future: func,
      builder: ((context, snapshot) {
        if (snapshot.connectionState ==
           ConnectionState.waiting) {
             return const CircularProgressIndicator();
           } else if (snapshot.connectionState ==
           ConnectionState.done) {
             if (snapshot.hasError) {
                setState(() {
                  !booling;
                });
                setState.call;
                return const Text('data1');
                } else {
                  return const Text('data2');
                }
             } else {
                return Text(snapshot.connectionState.toString());
             }
})))

Solution

  • You can use a StatefulWidget and put the func variable holding the future into a member of the state class. Initailize it first in the initState, and then you can restart the future using setState and re-assign the value of the future.

    But I really don't recommend to call it automatically on error. It could mean and endless loop if the error persists. Instead let the user invoke it with a button for example.

    import 'package:flutter/material.dart';
    
    class MyWidget extends StatefulWidget {
      @override
      MyWidgetState createState() => MyWidgetState();
    }
    
    class MyWidgetState extends State<MyWidget> {
      late Future<...> _future;
    
      @override
      void initState() {
        super.initState();
        _future = ...;
      }
    
      @override
      Widget build(BuildContext context) => FutureBuilder<...>(
          future: _future,
          builder: (context, snapshot) {
            ...
          });
    }
    

    To re-run the future:

    setState(() {
      _future = ...;
    });