Home > Software design >  How to do never finishing Futures in Dart/Flutter?
How to do never finishing Futures in Dart/Flutter?

Time:04-03

Imagine the following scenario: A widget shows a "Loading" screen until an async callback completes, then it switches to a different widget.

I'm trying to test it, specifically the part that shows the "Loading" screen. So what I tried to do was mock the async callback and set it to something like Future.delayed(Duration(days: 1)) so that I can be sure that it will never finish within that specific test.

That seems to work, but then flutter gets angry at me and reports issues about pending timers. For some reason all timers have to finish for a test to finish successfully.

So how do I write this test case the correct way? How can I create a future that will never finish and not run into issues with timers?

CodePudding user response:

As I was about to give up, I found out from Dart docs that Future.any([]) essentially achieves this.

If [futures] is empty, or if none of its futures complete, the returned future never completes.

CodePudding user response:

Another solution would be to use Completer.

future: Completer().future,

will do the trick. However, reading your description, I get the feeling that you might want to rethink your approach since having the need for a never completing future sounds like your code in itself might be the issue.

  • Related