How to run code after some delay in Flutter?
I'd like to execute a function after a certain delay after my Widget is built. What's the idiomatic way of doing this in Flutter?
What I'm trying to achieve:
I'd like to start with a default FlutterLogo
Widget and then change its style
property after some duration.
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.
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");
});
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,
);
}
}
Just leaving here the snippet everyone is looking for:
Future.delayed(Duration(milliseconds: 100), () {
// Do something
});