Flutter: How do I retry a FutureBuilder when an error occurs?

116 Views Asked by At

I created a FutureBuilder that extends a Stateful Widget like this which accept Future and the onSuccess method.

Code updated following the example shared by Dhafin Rayhan:

class FutureResponseBuilder<T> extends StatefulWidget {
  final Future future;
  final Function(T) onSuccess;

  const FutureResponseBuilder(
      {required this.future, required this.onSuccess, super.key});

  @override
  State<FutureResponseBuilder<T>> createState() =>
      _FutureResponseBuilderState<T>();
}

class _FutureResponseBuilderState<T> extends State<FutureResponseBuilder<T>> {
  late Future<T> future = callAPI();

  Future<T> callAPI() async {
    return await widget.future;
  }

  @override
  Widget build(BuildContext context) => FutureBuilder(
      future: future,
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          if (snapshot.hasError) {
            return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  Text('OOPS!'),
                  Text('${snapshot.error}'),
                  Text('Please try again.'),
                  SizedBox(
                      width: 100,
                      child: FilledButton(child: const Text('OK'), onPressed: () {
                        future = callAPI();
                        setState(() {});
                      }))
                ]);
          } else if (snapshot.hasData) {
            return widget.onSuccess(snapshot.data as T);
          }
        }
        return const Center(child: CircularProgressIndicator());
      });
}

When the FutureBuilder has error, it will return a message and a button to allow user to retry when the button is pressed. However, when I pressed the button, I'm unable to rebuild the FutureBuilder with the setState. Is there a way for me to achieve this?

1

There are 1 best solutions below

0
Ashish Mathur On

create a key by using

 Key _refreshKey = UniqueKey();

assign to FutureBuilder Widget as

FutureBuilder(
          key:_refreshKey

in setState function assign new value to _refreshKey