【问题标题】:Define action when AlertDialog is dismissed by clicking outside定义通过单击外部关闭 AlertDialog 时的操作
【发布时间】:2020-07-16 21:05:34
【问题描述】:

我正在 Flutter 中制作一个简单的 TODO 应用程序。在每个项目旁边我都有一个“编辑”图标,它会打开一个 AlertDialog,其中包含该项目的预填描述和数量。当我在对话框外单击时,它按预期被关闭。对于这个表单,我使用了两个字符串变量descriptionamount,以及两个控制器descriptionControlleramountController

我还有“添加”按钮,它会打开一个类似表单的类似警报对话框,其中我使用相同的字符串变量和控制器。

问题出现在以下场景中: - 我点击某个项目的“编辑”按钮。对话框出现,带有预填充的字段。 - 我通过单击外部关闭对话框。 - 我点击“新建”按钮。对话框出现,但我仍然看到之前编辑的项目中的值,而不是空字段。

其中一种解决方案当然是使用单独的控制器。但我想知道是否有可能通过单击外部并执行特定操作(清除控制器)来检测对话框被关闭。

谢谢。

【问题讨论】:

  • 你可以这样做,解决方案在这里找到。 github.com/flutter/flutter/issues/26542
  • 不是最好的解决方案,但你可以试试这个 - 你可以做的是,当你关闭编辑对话框时,只需将值存储在文本变量中,然后设置 descriptionController.text=" ",或者只是在文本字段中使用 onChanged 方法并继续将值分配给文本变量,并在关闭时设置 descriptionController.text=""。

标签: flutter flutter-alertdialog


【解决方案1】:

这在许多情况下可能会有所帮助。 无需检测触摸/点击屏障/AlertDialog 外部,只需执行以下操作-

  • 提取AlertDialog 小部件并使其成为StatefulWidget
  • StatefulWidget 在结束/弹出时总是依次调用deactivate()dispose()。因此,当AlertDialog 被解除时,您可以在任何这些函数中执行您想要执行的任何特定操作(根据您的需要)。
  • AlertDialog 使用Android 后退按钮或单击Barrier/outside 时,它​​将为您提供帮助。 您可能需要对AlertDialog 本身使用的任何按钮采取额外的预防措施,即单独检测该按钮单击,从而避免您仅在 Android 后退按钮或单击 Barrier/ 时才想做的任何操作outside 用于关闭AlertDialog

例如,假设您在AlertDialog 上使用TextButton

TextButton(
      child: const Text(
        'Continue',
        softWrap: true,
      ),
      onPressed: () {
        setState(() {
          isContinueButtonPressed = true;
        });
        Navigator.of(context)
            .popAndPushNamed(SomeScreen.routeName);
      },
    )

然后在deactivate() 和/或dispose() 里面,做这样的事情-

@override
void deactivate() {
 if (!isContinueButtonPressed){
   // do your actions if 'continue' button on AlertDialog is not pressed
 } 
 super.deactivate();
}

@override
void dispose() {
 if (!isContinueButtonPressed){
   // do your actions if 'continue' button on AlertDialog is not pressed
 } 
 super.dispose();
}

【讨论】:

    猜你喜欢
    • 2018-11-11
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    • 2016-11-20
    • 2021-11-24
    • 1970-01-01
    • 2018-08-18
    相关资源
    最近更新 更多