Flutter: Using Future.delayed without async
In Flutter, the Future.delayed
function is commonly used to introduce a delay in the code execution for a specific period of time. However, using Future.delayed
requires marking the function as async
, and using the await
keyword.
But what if you want to introduce a delay without creating an additional async function or using the await keyword? In this article, we will show you how to achieve this.
Using Future.delayed without async
To use Future.delayed
without the need for an async function, you can leverage the power of Dart’s Completer
class. The Completer
class is used to create custom implementations of futures.
Here’s an example of how you can use Future.delayed
without marking the function as async:
void delayFunction() {
Completer completer = Completer();
Duration delay = Duration(seconds: 2);
Timer(delay, () {
// Perform your desired task after the delay
completer.complete();
});
completer.future.then((_) {
// Execute the code after completion
print('Task completed successfully!');
});
}
In the code above, we create a Completer
object and set a duration for the delay (in this case, 2 seconds). We then use the Timer
function to execute the task after the specified delay. Once the task is completed, we call completer.complete()
.
Finally, we can use the then
method on the completer.future
to execute the code block after the completion.
Conclusion
Using Future.delayed
without marking the function as async can be helpful in scenarios where introducing a delay is needed, but creating an additional async function is not desired. By leveraging Dart’s Completer
class, you can achieve the same result without introducing unnecessary complexity.
Remember to import the necessary packages:
import 'dart:async';