Reputation: 45
How can I add a wait time in dart/flutter.
I have two blocks of code to be executed after an if else statement
.
I want to add some time between them because the first one got a message to display to the user.
if(test==true){
print("Hello"};
//wait time added here
print("This hello after 5 secondes");
}
Upvotes: 0
Views: 1942
Reputation: 71623
There is any number of ways to do it, depending on how you want it to work, and whether your function is already asynchronous.
In general, you cannot insert a delay into a function which isn't asynchronous, not without blocking everything else.
If you don't want anything to happen in-between, and don't mind blocking,
you can use sleep
from dart:io
sleep(const Duration(seconds: 5));
or if you are on the web, and don't have dart:io
, you can busy-wait:
var sw = Stopwatch()..start();
while (sw.elapsedMilliseconds < 5000) {}
Both block any other computation from happening in the same isolate. The latter also spends a lot of CPU power doing it.
If your don't want to block (you usually don't), and your function
is already asynchronous (returns a future, is marked async
),
you can easily insert a non-blocking pause:
// before the pause
await Future.delayed(const Duration(seconds: 5));
// rest of function
Consider making your function asynchronous if it isn't already.
If you don't want to block, but your function is not asynchronous, then you need to start an asynchronous operation, and put the rest of your function into that, so that it will execute later. Then your function returns (synchronously), so no-one will be able to wait for the delayed part to happen. You can use any of:
Timer(const Duration(seconds: 5), () {
// rest of function.
});
or
unawaited(Future.delayed(const Duration(seconds: 5), () {
// rest of function.
}));
or even introduce a local async
function
unawaited(() async {
await Future.delayed(const Duration(seconds: 5));
// rest of function.
}());
Upvotes: 3
Reputation: 23
I think it also possible to use Timer
as well:
Timer(Duration(seconds: 5), () => print("This hello after 5 seconds"));
Upvotes: 0
Reputation: 363
you can use Future.delayed
to acheive that.
if(test==true){
print("Hello");
Future.delayed(const Duration(seconds: 5), () {
print("This hello after 5 secondes");
});
}
Upvotes: 0
Reputation: 45
Solution:
Below is an example to Future.delayed method :
Future.delayed(const Duration(seconds: 1,milliseconds: 600), () {
// Here you can write your code
});
Upvotes: 0
Reputation: 1757
You can try this:
Future.delayed(Duration(seconds: 5), () => print('This hello after 5 seconds'));
Upvotes: 0