如何使用后退/下一步浏览器按钮在 Flutter Web 中正确导航?

Fra*_*las 6 dart flutter flutter-web

我目前正在使用 Flutter Web 使用 flutter_modular 进行路由,当您通过浏览器直接导航到页面时,该路由可以正常工作,但在尝试返回然后再次下一个页面时遇到了问题。

让我解释一下,假设你在主页上,导航到注册页面,然后你按浏览器中的后退按钮,然后你想按浏览器中的下一步按钮,但你不能,因为 Flutter 处理了最后一页,它不再存在于浏览器历史记录中。

有没有办法在 Flutter Web 中实现干净流畅的导航?

小智 3

我最近也遇到了同样的问题。我通过 Flutter Navigation 2.0 找到了解决方案。我的主要问题是,

  • 单击浏览器刷新按钮后导航历史记录消失
  • 单击刷新按钮后,后退按钮仅起作用一次
  • 浏览器下一个按钮从未启用

这些问题在实现 Flutter Navigation 2.0 后都消失了。下面是简单的测试代码。您可以创建测试项目并复制和粘贴并检查您的要求是否合适。

import 'package:flutter/material.dart';
import 'package:get/get.dart';

void main() {
  runApp(GetMaterialApp.router(
    debugShowCheckedModeBanner: false,
    defaultTransition: Transition.fade,
    getPages: AppPages.pages,
    routerDelegate: AppRouterDelegate(),
  ));
}

abstract class Routes {
  static const HOME = '/';
  static const LOGIN = '/login';
  static const SIGNUP = '/signup';
}

class AppRouterDelegate extends GetDelegate {
  @override
  Widget build(BuildContext context) {
    return Navigator(
      onPopPage: (route, result) => route.didPop(result),
      pages: currentConfiguration != null
          ? [currentConfiguration!.currentPage!]
          : [GetNavConfig.fromRoute(Routes.HOME)!.currentPage!],
    );
  }
}

abstract class AppPages {
  static final pages = [
    GetPage(
      name: Routes.HOME,
      page: () => Home(),
    ),
    GetPage(
      name: Routes.LOGIN,
      page: () => Login(),
    ),
    GetPage(
      name: Routes.SIGNUP,
      page: () => Signup(),
    ),
  ];
}

class Home extends StatelessWidget {
  const Home({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.red,
      child: TextButton(
        child: Text(
          'Home',
          style: TextStyle(color: Colors.white),
        ),
        onPressed: () => Get.rootDelegate.toNamed(Routes.LOGIN),
      ),
    );
  }
}

class Login extends StatelessWidget {
  const Login({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.orange,
      child: TextButton(
        child: Text(
          'Login',
          style: TextStyle(color: Colors.white),
        ),
        onPressed: () => Get.rootDelegate.toNamed(Routes.SIGNUP),
      ),
    );
  }
}

class Signup extends StatelessWidget {
  const Signup({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue,
      child: TextButton(
        child: Text(
          'Signup',
          style: TextStyle(color: Colors.white),
        ),
        onPressed: () => Get.rootDelegate.toNamed(Routes.HOME),
      ),
    );
  }
}

Run Code Online (Sandbox Code Playgroud)

我在这篇博客中写了详细的解释。我使用了GetX包,但你也可以将这种做法与MaterialApp.router.

https://dev.to/swimmingkiim/flutter-web-fix-refresh-back-button-problem-4gk3