Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FLUTTER: How to show dialog before beginning of the app?

Tags:

flutter

dart

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?

like image 569
Ara Mkrtchyan Avatar asked Feb 09 '19 20:02

Ara Mkrtchyan


3 Answers

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(),
        );
      }
like image 82
Figen Güngör Avatar answered Oct 20 '22 15:10

Figen Güngör


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);   
  }
like image 4
Ara Mkrtchyan Avatar answered Oct 20 '22 15:10

Ara Mkrtchyan


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

like image 2
Jitesh Mohite Avatar answered Oct 20 '22 14:10

Jitesh Mohite