简体   繁体   English

如何获取Flutter中的当前路由路径?

[英]How to get current route path in Flutter?

While implementing persistent bottom bar , previous route need to be restored when a button in the bottom bar was clicked.在实现持久底部栏时,单击底部栏中的按钮时需要恢复以前的路线

When a button in the bottom bar is clicked, its current route path ( /a/b/c ) is saved and previously saved route is restored according to the button click.当点击底部栏中的按钮时,将保存其当前路径( /a/b/c ),并根据按钮点击恢复之前保存的路径。

Conceptually user will think each button as a workspace and its state is never get lost (including back stack).从概念上讲,用户会将每个按钮视为一个工作区,并且它的 state 永远不会丢失(包括返回堆栈)。 User can safely switch from one workspace to another.用户可以安全地从一个工作区切换到另一个工作区。

How to get current route path in Flutter, when the routing isrewinding to root ? Flutter 中路由倒带到 root时,如何获取当前路由路径?

这应该给你确切的路线名称

ModalRoute.of(context).settings.name

NavigatorState doesn't expose an API for getting the path of the current route, and Route doesn't expose an API for determining a route's path either. NavigatorState没有公开获取当前路由路径的 API, Route也没有公开确定路由路径的 API。 Routes can be (and often are) anonymous.路由可以(并且通常是)匿名的。 You can find out if a given Route is on the top of the navigator stack right now using the isCurrent method, but this isn't very convenient for your use case.您现在可以使用isCurrent方法确定给定的Route是否位于导航器堆栈的顶部,但这对您的用例来说不是很方便。

I would recommend that you take a different approach to this problem and don't rewind to the root at all.我建议您对这个问题采取不同的方法,根本不要回到根本。 Instead, use a different Navigator widget for each pane of the BottomNavigationBar .相反,对BottomNavigationBar每个窗格使用不同的Navigator小部件。 That way, you won't have to rewind the stack when switching between panes.这样,在窗格之间切换时就不必倒带堆栈。 You can wrap your Navigator widgets in Opacity and IgnorePointer widgets to hide them when they aren't supposed to be visible without destroying their stack.您可以将Navigator小部件包装在OpacityIgnorePointer小部件中,以在它们不可见时隐藏它们,而不会破坏它们的堆栈。

应用视频

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class SecurePage extends StatelessWidget {
  final int index;

  SecurePage(this.index);

  Widget build(BuildContext context) {
    return new Material(
      color: Colors.amber,
      child: new InkWell(
        child: new Center(
          child: new Icon(
            Icons.security,
            color: Colors.white,
            size: index * 100.0 + 20.0,
          ),
        ),
        onTap: () {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (BuildContext context) {
                return new SecurePage(index + 1);
              },
            ),
          );
        },
      ),
    );
  }
}

class VerifiedPage extends StatelessWidget {
  final int index;

  VerifiedPage(this.index);

  Widget build(BuildContext context) {
    return new Material(
      color: Colors.green,
      child: new InkWell(
        child: new Center(
          child: new Icon(
            Icons.verified_user,
            color: Colors.white,
            size: index * 100.0 + 20.0,
          ),
        ),
        onTap: () {
          Navigator.of(context).push(
            new MaterialPageRoute(
              builder: (BuildContext context) {
                return new VerifiedPage(index + 1);
              },
            ),
          );
        },
      ),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  State createState() => new MyHomePageState();
}

class MyHomePageState extends State<MyHomePage> {
  int _page = 0;
  List<Widget> initialWidgets = <Widget>[
    new SecurePage(0),
    new VerifiedPage(0),
  ];

  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Stack(
        children: new List<Widget>.generate(initialWidgets.length, (int index) {
          return new IgnorePointer(
            ignoring: index != _page,
            child: new Opacity(
              opacity: _page == index ? 1.0 : 0.0,
              child: new Navigator(
                onGenerateRoute: (RouteSettings settings) {
                  return new MaterialPageRoute(
                    builder: (_) => initialWidgets[index],
                  );
                },
              ),
            ),
          );
        }),
      ),
      bottomNavigationBar: new BottomNavigationBar(
        currentIndex: _page,
        onTap: (int index) {
          setState(() {
            _page = index;
          });
        },
        items: <BottomNavigationBarItem>[
          new BottomNavigationBarItem(
            icon: new Icon(Icons.security),
            title: new Text('Secure'),
          ),
          new BottomNavigationBarItem(
            icon: new Icon(Icons.verified_user),
            title: new Text('Verified'),
          ),
        ],
      ),
    );
  }
}

Posting this answer mainly for archival purposes, but as @ikben mentioned, one way to get the current route, and all its properties, is ModalRoute.of(context) .发布此答案主要是为了存档目的,但正如@ikben 所提到的,获取当前路线及其所有属性的一种方法是ModalRoute.of(context) This returns a ModalRoute , which despite its name, applies to most Navigator.push calls, not just showDialog .这将返回一个ModalRoute ,尽管它的名字适用于大多数Navigator.push调用,而不仅仅是showDialog Helpful properties include Route.settings , Route.navigator , and Route.isFirst .有用的属性包括Route.settingsRoute.navigatorRoute.isFirst

While implementing persistent bottom bar , previous route need to be restored when a button in the bottom bar was clicked.在实现持久性底部栏时,单击底部栏上的按钮时,需要恢复以前的路线

When a button in the bottom bar is clicked, its current route path ( /a/b/c ) is saved and previously saved route is restored according to the button click.单击底部栏中的按钮时,将保存其当前路径路径( / a / b / c ),并根据该按钮单击恢复先前保存的路径。

Conceptually user will think each button as a workspace and its state is never get lost (including back stack).从概念上讲,用户会将每个按钮视为一个工作区,并且其状态永远不会丢失(包括后退堆栈)。 User can safely switch from one workspace to another.用户可以安全地从一个工作区切换到另一个工作区。

How to get current route path in Flutter, when the routing isrewinding to root ?当路由重绕到根时,如何在Flutter中获取当前路由路径?

I found a much simpler solution.我找到了一个更简单的解决方案。 I love StatelessWidget's so I did it with a static, but you can do it with a StatefulWidget.我喜欢 StatelessWidget 的所以我用静态来做,但你可以用 StatefulWidget 来做。 You'll need a StatefulWidget if you have hierarchical navigation.如果您有分层导航,您将需要一个 StatefulWidget。 This is a tile in my NavDrawer.这是我的 NavDrawer 中的一个磁贴。 (Statics get a bad rap but in a UI it's not bad, there's only one process running a single thread.) (静态的名声不好,但在 UI 中还不错,只有一个进程在运行单个线程。)

class NavListTile extends StatelessWidget {
  static String currentRoute = 'dashboard';
  final String route;

  const NavListTile({
    Key? key,
    required this.route,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var isCurrent = currentRoute == route;
    String suffix = isCurrent ? '_green' : '';
    return ListTile(
      title: NavMenuItem(capitalizedRoute, isCurrent,
          "assets/images/" + route + suffix + ".png", context),
      onTap: () {
        currentRoute = route;
        Navigator.of(context).pushNamed('/' + route);
      },
    );
  }
}

In case if you want to get current route by use navigator key, possible to use popUntil method for it:如果您想通过使用导航键获取当前路线,可以使用 popUntil 方法:

String? currentPath;
navigatorKey.currentState?.popUntil((route) {
  currentPath = route.settings.name;
  return true;
}); 

If you are using go_router package you can use the below code:如果您使用的是 go_router package,您可以使用以下代码:

GoRouter.of(context).location

I'm using go_router in my project.我在我的项目中使用 go_router。 In go_router, you access current route as below在 go_router 中,你访问当前路由如下

    var currentRoute = GoRouter.of(context).location;

If you're using go_router :如果您使用的是go_router

GoRoute(
  name: 'login',
  path: '/login',
  builder: (context, state) => LoginScreen(),
),

use this用这个

GoRouterState.of(context).path

for named routes use:对于命名路线,请使用:

GoRouterState.of(context).name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM