LoginSignup
6
0
記事投稿キャンペーン 「2024年!初アウトプットをしよう」

[Flutter 3.16対応]WillPopScopeからPopScopeに変えるときの注意点

Last updated at Posted at 2024-01-30

まえおき

Flutter3.16対応時にWillPopScopeがdeprecatedになるため、今後はPopScopeを使う必要があり、その際に1点罠にハマったのでメモ

概要

PopScopeonPopInvoked内でNavigator.of(context).pop();を使用するとonPopInvokedが呼ばれてしまいます。

PopScope(
    canPop: false,
    onPopInvoked: (didPop) async {
        if (await webViewController.canGoBack()) {
            await controller.goBack();
        } else {
            if (context.mounted) {
                Navigator.of(context).pop();
            }
        }
  }...
);

対策

popが行われるさいはdidPopがtrueになるので、canPopを常にfalseにしている場合は、didPopがtrueの場合は処理を行わないようにすれば回避できます。

PopScope(
    canPop: false,
    onPopInvoked: (didPop) async {
        if (didPop) {
            return;
        }
        if (await controller.canGoBack()) {
            await controller.goBack();
        } else {
            if (context.mounted) {
                Navigator.of(context).pop();
            }
        }
  }...
);

感想

そもそもWillPopScope時のコードをそのまま使っているのが悪い気がするので、PopScopeに合わせて書き直した方がいいのかなと思います。

追記(2024/02/01)

iOSにてcanPopをfalseにするとback gestureがうまく動かないようです。

PopScope does not invoke onPopInvoked for iOS back gesture when canPop set to false · Issue #138624 · flutter/flutter
https://github.com/flutter/flutter/issues/138624

6
0
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
6
0