WillPopScope 在 flutter 3.12 后已弃用

dha*_*rmx 12 flutter

当我们在 flutter 版本 3.12.0 之后使用下面的代码时,我们收到了已弃用的消息,现在该使用什么代替呢?

WillPopScope(
          onWillPop: () {
            setStatusBarColor(statusBarColorPrimary,statusBarIconBrightness: Brightness.light);
            finish(context);
            return Future.value(true);
          },)
Run Code Online (Sandbox Code Playgroud)

dha*_*rmx 14

WillPopScope在 flutter 之后已被弃用v3.12.0-1.0.pre。

现在您可以使用PopScope如下:

return PopScope(
    canPop: true, //When false, blocks the current route from being popped.
    onPopInvoked: (didPop) {
        //do your logic here:
        setStatusBarColor(
            statusBarColorPrimary,
            statusBarIconBrightness: Brightness.light,
        );
        finish(context);
    },
    child: Scaffold(/*other child and ui etc*/),
);
Run Code Online (Sandbox Code Playgroud)

  • 但是我们如何在“canPop”中执行异步操作呢? (4认同)
  • 知道如何在不执行两次“onPopInvoked”方法的情况下发送数据吗? (2认同)

Mau*_*rix 5

如果您确实需要条件异步导航,您可以这样做:

      PopScope(
          canPop: false, // prevent back
          onPopInvoked: (_) async {
            // This can be async and you can check your condition
            final backNavigationAllowed = await something();
            if (backNavigationAllowed) {
              // Manually navigate back
              if (mounted) Navigator.of(context).pop();
            } else {
              // User is still on the same page, do whatever you want
            }
          },
          child: ...
      );
Run Code Online (Sandbox Code Playgroud)