简体   繁体   English

FLUTTER:如何在应用程序开始之前显示对话框?

[英]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? showDialog() 方法需要一个上下文,因此我应该将它与 buildContext 放在某个地方,我假设在应用程序的构建方法中,但是如何在屏幕上构建实际布局之前触发对话框?

In your initState you can add your callback which will show your dialog with WidgetsBinding.instance.addPostFrameCallback which will be displayed immediately after layout.在您的initState您可以添加您的回调,该回调将显示您的对话框和WidgetsBinding.instance.addPostFrameCallback ,它将在布局后立即显示。 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 1. WidgetsBinding

WidgetsBinding.instance.addPostFrameCallback((_) {
 showDialog();
});

2. SchedulerBinding 2.调度器绑定

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. WidgetsBindingSchedulerBinding只会像我们在initState(),调用的那样被调用一次initState(),但请记住它会在 build 方法完成渲染时调用。

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详细说明: https : //medium.com/flutterworld/flutter-schedulerbinding-vs-widgetsbinding-149c71cb607f

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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