start(); // do something to wait for 2 seconds await Future. delayed(const Duration(seconds: 2), (){}); expect(timer. seconds, startTime - 2); });
Creating a simple timer Now, to create a simple 3-second timer, add the following, which triggers a callback after it executes: final timer = Timer( const Duration(seconds: 3), () { // Navigate to your favorite place }, ); Once the callback triggers, we can navigate a user to a new screen, for example.
Future<T>. delayed constructor Null safetyCreates a future that runs its computation after a delay. The computation will be executed after the given duration has passed, and the future is completed with the result of the computation.
You can use Future.delayed
to run your code after some time. e.g.:
Future.delayed(const Duration(milliseconds: 500), () {
// Here you can write your code
setState(() {
// Here you can write your code for open new view
});
});
In setState function, you can write a code which is related to app UI e.g. refresh screen data, change label text, etc.
Figured it out 😎
class AnimatedFlutterLogo extends StatefulWidget {
@override
State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
}
class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
Timer _timer;
FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;
_AnimatedFlutterLogoState() {
_timer = new Timer(const Duration(milliseconds: 400), () {
setState(() {
_logoStyle = FlutterLogoStyle.horizontal;
});
});
}
@override
void dispose() {
super.dispose();
_timer.cancel();
}
@override
Widget build(BuildContext context) {
return new FlutterLogo(
size: 200.0,
textColor: Palette.white,
style: _logoStyle,
);
}
}
Trigger actions after countdown
Timer(Duration(seconds: 3), () {
print("Yeah, this line is printed after 3 seconds");
});
Repeat actions
Timer.periodic(Duration(seconds: 5), (timer) {
print(DateTime.now());
});
Trigger timer immediately
Timer(Duration(seconds: 0), () {
print("Yeah, this line is printed immediately");
});
Just leaving here the snippet everyone is looking for:
Future.delayed(Duration(milliseconds: 100), () {
// Do something
});
You can do it in two ways 1 is Future.delayed
and 2 is Timer
Using Timer
Timer
is a class that represents a count-down timer that is configured to trigger an action once end of time is reached, and it can fire once or repeatedly.
Make sure to import dart:async
package to start of program to use Timer
Timer(Duration(seconds: 5), () {
print(" This line is execute after 5 seconds");
});
Using Future.delayed
Future.delayed
is creates a future that runs its computation after a delay.
Make sure to import "dart:async";
package to start of program to use Future.delayed
Future.delayed(Duration(seconds: 5), () {
print(" This line is execute after 5 seconds");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With