Terminate a function in dart/flutter

2.2k views Asked by At

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

1

There are 1 answers

0
Omatt On

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.