3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Flutter】PopScopeの使い方とonPopInvokedWithResult()実装のポイント

Last updated at Posted at 2024-10-27

はじめに

FlutterのPopScopeを使用して、Androidで戻るジェスチャ(OSの戻るボタンや横スワイプ)が実行されたときの処理の追加方法を紹介します。

PopScopeの使い方

最上位のウィジェットをラップして使用します。

class SampleView extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return PopScope(
      child: Scaffold(
        ...省略...
      )
    )
  }
}

PopScope()の引数にcanPop: falseとonPopInvokedWithResult()を追加します。

    return PopScope(
      canPop: false,
      onPopInvokedWithResult: (didPop, __) async {
        if (didPop == true) return;

        if (isEditing) {
            // 画面遷移して良いか確認する
            if (isOk) {
              Navigator.of(context).pop();
            }
        }else {
            Navigator.of(context).pop();
        }
      },
      child: Scaffold(
        ...省略...
      )
    )

canPop: システムの戻るジェスチャによりpopさせるかの設定。自分の意図したタイミングでpopさせるためfalseにする。
onPopInvokedWithResult(): popが試みられたとき(戻るジェスチャが使用されたときと、Navigator.of(context).pop();が実行されたとき)に発火する。
didPop: 戻る操作が成功したかを示す。成功した場合はこれ以上処理しないためにreturnする。

ポイント

canPop:falseを設定している状態で戻るジェスチャを使用すると、onPopInvokedWithResult()didPopd:falseの状態で発火します。これを利用してバックボタンを押したときの動作を制御します。

onPopInvokedWithResult()内で画面をpopする処理を入れるとき、didPopのガード節を入れないと、onPopInvokedWithResult()が再帰的に呼び出され、エラーが発生します。

まとめ

ドキュメントを読んでもよくわからない箇所が多かったので検証しつつ記事にまとめました。このあたりもう少し直感的になってくれると嬉しいですね。

ここまで読んでいただけた方はいいね・ストックをよろしくお願いします。

Flutter製の便利すぎる単語帳アプリBestflipを配信しているのでそちらも見ていただけたら嬉しいです。

参考文献

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?