I have been trying to find any information about creating a Widget that disappears after a period of time. I am trying to create a greeting page that appears once the app runs and disappears after a couple of seconds; navigating to my home page afterwards.
What is the correct direction in order to get this done?
I understand how to use showDialog with buttons, but I want the greetings view to be the very first view when the app starts, so how to correctly use showDialog?
void main() {
runApp( new MaterialApp(
home: new SignIn(),//how to integrate showDialog with my flow
))
}
You can use Timer and the Navigator for such a thing.
We can think of a stateful TimedWidget, invoked with
showDialog(child: new TimedWidget(), context: context);
And the code of that widget would have something like :
initState() {
super.initState();
timer = new Timer(const Duration(seconds: 5), onCloseDialog);
}
void onCloseDialog() {
if (mounted) {
Navigator.of(context).pop();
}
}
Edit :
You may have noticed that you can't do showDialog/NavigatorState.push inside the build method. If you really want to have your page/popin directly without pressing any buttons, you have a few solutions.
For a page, you can think of directly loading your GreetingPage into the runApp. And then, the Greeting page will redirect after a few seconds to the according home. Typically, you'd have something like this in your GreetingPage :
initState() {
super.initState();
new Timer(const Duration(seconds: 5), onClose);
}
void onClose() {
Navigator.of(context).pushReplacement(new PageRouteBuilder(
maintainState: true,
opaque: true,
pageBuilder: (context, _, __) => new Home(),
transitionDuration: const Duration(milliseconds: 250),
transitionsBuilder: (context, anim1, anim2, child) {
return new FadeTransition(
child: child,
opacity: anim1,
);
}));
}
Easier, for a dialog you can have use another timer to delay the apparition of your dialog by a frame. Here you'd have this :
initState() {
super.initState();
new Timer(const Duration(), () {
showDialog(context: context, child: new SimpleDialog(
title: new Text("Hello world"),
));
});
}
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