Flutter Web:如何在Flutter Web应用程序中禁用浏览器的后退按钮

5

用户成功登录后,将被重定向到主页,但当用户单击浏览器的“返回”按钮时,很容易被重定向回登录界面。我该怎么做才能禁用后退重定向?

2个回答

4
class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    /// Hope WillPopScope will do the job for you.
    return WillPopScope(
      onWillPop: () async => null,
      child: Scaffold(
        body: Center(
          child: Text('asd'),
        ),
      ),
    );
  }
}

它工作得很好,但是当我刷新页面时,会出现同样的问题,它会重定向到登录界面。 - Olance
登录是我的初始路由。 - Olance
@Olance 你可以查看这个链接 https://pub.dev/packages/universal_html 来帮助存储会话。 - Federick Jonathan
1
我有同样的问题。这对我没有用。当我在我的Flutter Web应用程序上使用浏览器返回按钮时,onWillPop不会触发。有什么方法可以防止回到登录屏幕? - tmaihoff

1
更新@FederickJonathan的答案,针对2023年,现在你需要像这样返回一个布尔值来作为onWillPop参数:
class SecondPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    /// Hope WillPopScope will do the job for you.
    return WillPopScope(
      onWillPop: () async => false, // update here
      child: Scaffold(
        body: Center(
          child: Text('asd'),
        ),
      ),
    );
  }
}

你还可以将它包装在 main.dart 文件中的 MaterialApp 类中,以便一次性为整个应用程序工作,就像这样:
class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async => false,
      child: MaterialApp(
       ...
      ),
    );
  }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接