📅  最后修改于: 2023-12-03 14:47:28.840000             🧑  作者: Mango
Sleeping in programming refers to delaying the execution of a program for a certain amount of time. In Dart, you can make use of the Future
class along with the async
and await
keywords to introduce pauses or delays in your code execution. This can be useful in scenarios where you want to wait for a certain period of time before proceeding with the rest of the code.
The general syntax to sleep in Dart is as follows:
import 'dart:async';
void main() async {
// Delay for 2 seconds
await Future.delayed(Duration(seconds: 2));
// Rest of the code
}
async
is used to define an asynchronous function, which allows the usage of await
keyword inside it.await
keyword is used to pause the execution of the function until the awaited expression is completed.Future.delayed()
method is used to create a Future
that completes after a specified duration. The duration is specified using the Duration
class.import 'dart:async';
void main() async {
print('Start');
await Future.delayed(Duration(seconds: 2));
print('Paused for 2 seconds');
await Future.delayed(Duration(milliseconds: 500));
print('Paused for 500 milliseconds');
// Rest of the code
}
Start
Paused for 2 seconds
Paused for 500 milliseconds
In the example above, the program starts execution and then pauses for 2 seconds using await Future.delayed(Duration(seconds: 2))
. After that, it prints "Paused for 2 seconds". Similarly, it pauses for 500 milliseconds using await Future.delayed(Duration(milliseconds: 500))
and prints "Paused for 500 milliseconds".
Note: Sleeping should be used judiciously as it may lead to unresponsive or sluggish behavior in your application if not used properly.