【问题标题】:FLUTTER: How to show dialog before beginning of the app?颤振:如何在应用程序开始之前显示对话框?
【发布时间】:2019-07-03 17:55:35
【问题描述】:

我想在打开应用程序之前显示一个确认警报对话框,有人可以告诉我如何在颤振中实现这一点吗?

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

【问题讨论】:

    标签: dart flutter


    【解决方案1】:

    在您的initState 中,您可以添加您的回调,它将显示您与WidgetsBinding.instance.addPostFrameCallback 的对话框,该对话框将在布局后立即显示。您可以根据对话结果更新布局状态。

    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(),
            );
          }
    

    【讨论】:

    • WidgetsBinding.instance .addPostFrameCallback((_) 不再起作用。stackoverflow.com/a/54553143/10269042
    • 是的,我也尝试过,但不工作,尝试了另一种方法,如果其他人需要,我会在答案中发布..
    • UPSS。它适用于我的版本=) 你在哪个版本上?
    • 在最新的稳定颤振版本上。
    【解决方案2】:

    下面的代码有效,我想这就是答案

      @override
      Widget build(BuildContext context) {
        Future.delayed(Duration.zero, () => showAlert(context));
        return new WhateverLayoutYouWantToBeDisplayed();
      }
    
      void showAlert(BuildContext context) {
        showDialog(
          child: new WhateverCustomDialogYouHave(),
            context: context);   
      }
    

    【讨论】:

    • build 方法调用showDialog 不是一个好主意,因为build 可以在整个屏幕生命周期内多次调用。
    【解决方案3】:

    最好的方法,

    1.小部件绑定

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

    2。调度器绑定

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

    WidgetsBinding & SchedulerBinding 只会被调用一次,就像我们在 initState(), 中调用的一样,但请记住,它将在构建方法完成渲染时调用。

    void initState() {
      // TODO: implement initState
      super.initState();
      print("initState");
      WidgetsBinding.instance.addPostFrameCallback((_) {
        print("WidgetsBinding");
      });
      SchedulerBinding.instance.addPostFrameCallback((_) {
        print("SchedulerBinding");
      });
    }
    

    详细说明: https://medium.com/flutterworld/flutter-schedulerbinding-vs-widgetsbinding-149c71cb607f

    【讨论】:

      猜你喜欢
      • 2022-11-11
      • 1970-01-01
      • 1970-01-01
      • 2011-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多