9

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?

Ara Mkrtchyan
  • 497
  • 6
  • 12

3 Answers3

9

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(),
        );
      }
Figen Güngör
  • 12,169
  • 14
  • 66
  • 108
5

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);   
  }
Ara Mkrtchyan
  • 497
  • 6
  • 12
  • 8
    It's not a good idea to invoke `showDialog` from `build` method because `build` can be called multiple times throughout screen lifetime. – flomaster Feb 26 '20 at 09:27
3

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");
  });
}
sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Jitesh Mohite
  • 31,138
  • 12
  • 157
  • 147