首页 > 解决方案 > Navigator.push 是否可以显示不同的链接页面?

问题描述

我正在通过 Flutter for web 进行开发。

目前可以从主页转到个人资料页面,但是否可以将这些 URL 分开?例如:

主页:https://testapp.com/home

个人资料页面:https://testapp.com/profile

当我执行该profilePage()功能时,Navigator.push将带我到个人资料页面。

   void profilePage() {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => showProfile(),
      ),
    );
  }

showProfile使用不同的 dart 文件执行以完成页面导航。

 class showProfile extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          backgroundColor: Colors.white,
          title: const Center(
            child: Text("Test App",
                style:
                    TextStyle(color: Colors.black)),
          )),
      body: Container(
        height: double.infinity,
        color: Colors.white,
      ),
    );
  }
}

目前,主页和个人资料页面具有相同的 URL (https://testapp.com/#/)。因此,即使用户键入 testapp.com/profile,也无法跳转到个人资料页面。我的目的是在 Navigator 中转到不同的 URL。

谢谢你。

标签: flutterdartflutter-web

解决方案


添加依赖项/插件。

现在,创建一个名为 routing.dart 的文件并添加以下代码:-

    class FluroRouting {
      static final router = FluroRouter();
      static Handler _profileHandler = Handler(
          handlerFunc: (BuildContext context, Map<String, dynamic> params) =>
              Profile());
      static Handler _homeHandler = Handler(
          handlerFunc: (BuildContext context, Map<String, dynamic> params) =>
              HomePage());
      static void setupRouter() {
        router.define('/home', handler: _homeHandler,);
        router.define('/profile', handler: _profileHandler,);
router.notFoundHandler = Handler(
        handlerFunc: (BuildContext? context, Map<String, dynamic> params) =>HomePage()
    );
      }
      static void navigateToPage({String routeName,BuildContext context}) {
        router.navigateTo(context, routeName, transition: TransitionType.none);
      }
      static void pushAndClearStackToPage({String routeName,BuildContext context}) {
        router.navigateTo(context, routeName, clearStack: true,transition: TransitionType.none);
      }
    }

现在您需要初始化和设置这些路由,因此将您的 void main 修改为:-

void main()async {
  FluroRouting.setupRouter();
  runApp(MyApp());
}
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'My Website',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      initialRoute: '/home',
      onGenerateRoute: FluroRouting.router.generator,
    );
  }
}

每当您需要导航时,只需使用以下代码:-

FluroRouting.navigateToPage(routeName:"/profile",context:context);

推荐阅读