3

I have a function witch returns a Future.

main(){
function().timeout(Duration(milliseconds: 100), onTimeout: () {
        print("exit function");
      });
}

Future<void>function()async{
  await Future.delay(Duration(milliseconds: 500);
  print("function was run");
  return Future.value(null);
}

I want to exit the function after the timeout. In the example above i expect the output exit function.

How ever, the output from the flutter console is:

exit function
function was run

Does anybody know how to generete my expected result?

  • function can be of any type.

Thanks for ur help

David Wild
  • 193
  • 1
  • 8
  • https://stackoverflow.com/questions/67012599/flutter-stop-futurebuilder-operation-in-between-process – Ibrahim Ali Apr 22 '21 at 17:11
  • You cannot cancel a `Future`. At best you can set a flag and have your `Future`'s computation check it to exit early. – jamesdlin Apr 22 '21 at 19:35

1 Answers1

0

It's not possible to cancel a Future function. As alternative, you may consider using Streams if it fits your use case. You can subscribe to a StreamSubscription and call cancel() if needed to. Here's a sample provided in a post.

Omatt
  • 8,564
  • 2
  • 42
  • 144