To use timers in DART, import the package ‘DART :async’; Timer class that can be configured to trigger one or more times.
Constructors
- Timer(Duration duration, void callback())
- Timer. Periodic (Duration Duration, void callback(Timer Timer)) Repeated Timer
Single timer
main() {
// Single timer
Timer(Duration(seconds: 2), () = > {print('This is a one-time timer with a 2 second delay.')});
}
Copy the code
Repeat timer
main() {
// Cancel the timer after I >10
num i = 1;
Timer.periodic(Duration(seconds: 1), (timer) {
print(timer.isActive); // true returns whether the timer is still active
print(timer.runtimeType); // the runtime type of the _Timer object
print(i++);
if (i > 10) {
print(timer.toString()); // Returns a string representation of this object
timer.cancel(); // You can use timer.cancel() to cancel the timer and avoid infinite callbacks
print(timer.hashCode); // Hash value of this object
print(timer.isActive); // false}}); }Copy the code
Timer.run() runs the given callback asynchronously as soon as possible
Timer.run(void Function() callback);
import 'dart:async';
main() {
var futureInstance = Future.value(12345);
for (var i = 0; i < 1; i++) {
Future.microtask(() => print('This is the future.microtask () microtask method'));
externalApproach();
print('First for loop:$i');
futureInstance.then((value) => print(value));
Timer.run(methods);
}
for (var i = 0; i < 2; i++) {
print('Second for loop:$i');
}
Timer(Duration(milliseconds: 0), () = > {print("Disposable timer.")});
}
void methods() async {
print("Run the given callback asynchronously as soon as possible");
}
void externalApproach() {
print("This is the external method.");
}
/* This is the external method first for loop: 0 second for loop: 0 second for loop: 1 12345 This is the future.microtask () microtask method as soon as possible to run the given callback one-time timer */
Copy the code