Flutter:如何避免在现有路线上推同一条路线 [英] Flutter: How to avoid pushing the same route on existing route

查看:81
本文介绍了Flutter:如何避免在现有路线上推同一条路线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有底部导航栏的视图,当您按下导航栏项目时,新的路线就会被推送到视图中.

I have view with bottom navigation bar, and when you push a navbar item, a new route is pushed into view.

 final navigatorKey = GlobalKey<NavigatorState>();

 @override
  Widget build(BuildContext context) => MaterialApp(
    home: Scaffold(
      key: _scaffoldKey,
      body: _buildBody(context),
      bottomNavigationBar: _buildBottomNavigationBar(context),
    ),
  );

 void routeToView(routeIndex) {
      navigatorKey.currentState.pushNamed(pagesRouteFactories.keys.toList()[routeIndex]);
  }

我想防止在当前视图上推送相同的路由.我想将当前路线与我们尝试推入的新路线进行比较,如果相同则忽略推入路线.

I would like to prevent same route being pushed on the current view. I want to compare the current route with new route we are trying to push, and ignore pushing the route if it is same.

如果要尝试的路线与我相同,我想将视图滚动到顶部

I want to scroll the view to the top if it is same route we are trying to push

任何想法.

推荐答案

NavigatorState没有公开用于获取路径的API 当前路线,并且Route不公开用于确定路线的API 路线的路径.路由可以是(通常是匿名的).你可以 找出给定的路线是否在导航器堆栈的顶部 现在使用isCurrent方法,但这对于 您的用例.

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. 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.

https://stackoverflow.com/a/46498543/2554745

这是我能想到的最接近的解决方案:

This is the closest solution I could think of:

Navigator.of(context).pushNamedAndRemoveUntil(
  "newRouteName",
  (route) => route.isCurrent && route.settings.name == "newRouteName"
      ? false
      : true);

如果路由名称为"newRouteName",则会弹出当前路由.然后再推送新的,否则将不会弹出任何内容.

It will pop the current route if name of the route is "newRouteName" and then push new one, else will not pop anything.

最新版本提供ModalRoute.of(context).settings.name来获取当前路线的名称.

Latest flutter provides ModalRoute.of(context).settings.name to get the name of current route.

这篇关于Flutter:如何避免在现有路线上推同一条路线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆