【问题标题】:Flutter - Problem combination of SchedulerBinding, showDialoag, AlertDialog and WillPopScopeFlutter - SchedulerBinding、showDialoag、AlertDialog和WillPopScope的问题组合
【发布时间】:2020-10-07 20:18:00
【问题描述】:

我有一个 AlertDialog 会在转到新屏幕时立即出现。它有 BACK 和 GO 按钮。仅当用户按下 GO 时,我才需要在关闭 AlertDialog 时留在此屏幕中。如果用户按下 BACK 按钮或 BACK Android 按钮,我需要转到上一个屏幕,而不是留在当前屏幕。 当我关闭 AlertDialog 时,我在 OK 的情况下使用 Navigator.pop(context, false),在 BACK 的情况下使用 Navigator.pop(context, true) 如果这是真的,则使用 bool 返回类型作为第二个 Navigator.pop(context)到上一个屏幕。

  @override
  void initState() {
    super.initState();
    SchedulerBinding.instance.addPostFrameCallback(
      (_) => _showDialog().then((isScreenToPop) {
     //ERROR: Unhandled Exception: Failed assertion: boolean expression must not be null
        if (isScreenToPop) {
          Navigator.pop(context);
        } else {
          setState(() {});
        }
      }),
    );
  }

现在我需要检测对 BACK Android 按钮的点击。为此,我将 WillPopScope 与 Future.value(true) 一起使用,但返回 null 并且使用第二个 Navigator.pop(context) 的评估返回 Unhandled Exception: Failed assertion: boolean expression must not be null。

  Future<bool> _showADialog() {
    return showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) {
        return WillPopScope(
          onWillPop: () async {
            //THIS RETURN NULL AND NOT Future<true>
            return Future.value(true);
          },
          child: StatefulBuilder(
            builder: (context, setState) {
              return AlertDialog(
                actions: <Widget>[
                  FlatButton(
                    child: Text('BACK'),
                    onPressed: () {
                      Navigator.pop<bool>(context, true);
                    },
                  ),
                  FlatButton(
                    child: Text('OK'),
                    onPressed: () {
                      Navigator.pop<bool>(context, false);
                    },
                  ),
                ],
              );
            },
          ),
        );
      },
    );
  }

暂时的解决方案如下,但我不喜欢。

        if (isScreenToPop == null || isScreenToPop) {
          Navigator.pop(context);
        } else {
          setState(() {});
        }

【问题讨论】:

    标签: android ios flutter dart


    【解决方案1】:

    只返回true 而不是Future.value(true)。当您使用async 时,返回值将自动返回为Future

    另外,如果您需要多次pop,请查看其他pop 函数,例如popUntil

    【讨论】:

    • 相同的断言空问题:return WillPopScope( onWillPop: () async { return true; },
    • 热重启。
    • 我认为onWillPop 不会向showDialog 调用者返回值,请尝试在那里调用pop(context, true) 以便返回一些内容。
    猜你喜欢
    • 2021-07-14
    • 2023-02-01
    • 1970-01-01
    • 2019-05-09
    • 1970-01-01
    • 2020-11-14
    • 2011-08-10
    • 1970-01-01
    • 2020-10-29
    相关资源
    最近更新 更多