I want to show a confirmation alert dialog right before opening the app, can someone please tell me how can I achieve that in flutter?
The showDialog() method needs a context, hence I should put it somewhere with buildContext, I assume in app's build method, but how can I trigger the dialog before the actual layout will be built on screen?
In your initState
you can add your callback which will show your dialog with WidgetsBinding.instance.addPostFrameCallback
which will be displayed immediately after layout. You can update your layout state according to your dialog result.
class HomePageState extends State<HomePage> {
@override
void initState() {
super.initState();
WidgetsBinding.instance
.addPostFrameCallback((_) => showDialog(...));
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('HomePage'),
),
body: Container(),
);
}
Code below works, I guess this is the answer
@override
Widget build(BuildContext context) {
Future.delayed(Duration.zero, () => showAlert(context));
return new WhateverLayoutYouWantToBeDisplayed();
}
void showAlert(BuildContext context) {
showDialog(
child: new WhateverCustomDialogYouHave(),
context: context);
}
Best ways of doing this,
1. WidgetsBinding
WidgetsBinding.instance.addPostFrameCallback((_) {
showDialog();
});
2. SchedulerBinding
SchedulerBinding.instance.addPostFrameCallback((_) {
showDialog();
});
WidgetsBinding
& SchedulerBinding
will be called only once as we called it in initState(),
but remember it will be called when the build method finished its rendering.
void initState() {
// TODO: implement initState
super.initState();
print("initState");
WidgetsBinding.instance.addPostFrameCallback((_) {
print("WidgetsBinding");
});
SchedulerBinding.instance.addPostFrameCallback((_) {
print("SchedulerBinding");
});
}
Detail Description: https://medium.com/flutterworld/flutter-schedulerbinding-vs-widgetsbinding-149c71cb607f
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