auto_route で WillPopScope の onWillPop で false を返している時は popForced を使って閉じる

pub.dev

画面遷移の際に type safe にできるので auto_route を使っているが、WillPopScope で囲んだ AlertDialog を閉じれずにハマった。

Android の戻るボタンでダイアログが閉じれないように WillPopScope で囲んだダイアログを作る。Android back ボタンは無効になるが、closeボタンを押してもダイアログが閉じない。

    return showDialog<void>(
      context: context,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return WillPopScope(
          onWillPop: () async => false,
          child: AlertDialog(
            content: Text('message'),
            actions: [
              TextButton(
                child: Text('close'),
                onPressed: () {
                  AutoRouter.of(context).pop();
                },
              ),
            ],
          ),
        );
      },
    );
  }

popForced

github.com

popForced を使えとのこと。AutoRouter.of(context).popForced(); にしたらダイアログが閉じれるようになった。