How can I retry a Future in Dart/Flutter?


I have a method that does some async processing and want it to retry X times. How can I achieve that in Dart/Flutter?


Use this function:

typedef Future<T> FutureGenerator<T>();
Future<T> retry<T>(int retries, FutureGenerator aFuture) async {
  try {
    return await aFuture();
  } catch (e) {
    if (retries > 1) {
      return retry(retries - 1, aFuture);


And to use it:

main(List<String> arguments) {

  retry(2, doSometing);


Future doSometing() async {
  print("Doing something...");
  await Future.delayed(Duration(milliseconds: 500));
  return "Something";

Answered By – Daniel Oliveira

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published