简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM