繁体   English   中英

如何从 NavigatorObserver 更新底部导航栏的 state?

[英]How to update the state of a bottom navigation bar from NavigatorObserver?

我正在创建一个底部导航栏,除了用户按下设备上的后退按钮外,一切正常。 导航栏的 state 不会更新以反映他们所在的页面。 为了解决这个问题,我发现了NavigatorObserver 现在我可以看到路由何时弹出,但我无法更新 state。 我的导航栏使用路线,因此当用户点击按钮时,它会推送一条新路线。 我正在尝试更新导航栏的索引,但我看不到这样做的方法。 导航栏使用StatefulWidget ,因此我可以使用setState回调。

我试过使用键,但我不能重复使用它们,因为它们在不同的Scaffold上。 我无法从NavigationObserver访问BuildContext ,因此我无法使用Provider之类的东西来通知更改和重建。

class CustomBottomNavBar extends StatefulWidget {
  @override
  _CustomBottomNavBarState createState() => _CustomBottomNavBarState();
}

class _CustomBottomNavBarState extends State<CustomBottomNavBar> {
  static int _selectedIndex;
  int get selectedIndex => _selectedIndex;
  set selectedIndex(int newIndex) {
    setState(() {
      _selectedIndex = newIndex;
    });
  }

  //...
}
class NavBarObserver extends NavigatorObserver {
  @override
  void didPop(Route route, Route previousRoute) {
    final navBarRoutes = Routes.all.sublist(0,4);
    final routeName = route.settings.name;
    if (navBarRoutes.contains(routeName)) {
      final index = navBarRoutes.indexOf(routeName);
      // selectedIndex = index;
    }
  }
}

你可以通过几种方式做到这一点。 这里我举了一个ValueNotifier的例子。 首先,您可以创建一个枚举来定义底部导航栏的不同页面。 然后你用你的枚举类型创建一个ValueNotifier并在NavBarObserverCustomBottomNavBar之间共享它。 NavBarObserver ,当发生任何选项卡更改时,您只需使用相应选项卡的枚举值更新ValueNotifier值。 您可以在_CustomBottomNavBarState中监听ValueNotifier值的变化来更新底部导航栏 state。

enum Tabs{one, two, three}

class CustomBottomNavBar extends StatefulWidget {
  final ValueNotifier<Tabs> tabsChangeNotifier;

  CustomBottomNavBar(this.tabsChangeNotifier);

  @override
  _CustomBottomNavBarState createState() => _CustomBottomNavBarState();
}

class _CustomBottomNavBarState extends State<CustomBottomNavBar> {
  Tabs _currentTab;

  @override
  void initState() {
    super.initState();
    widget.tabsChangeNotifier.addListener(() {
       setState(() {
         _currentTab = widget.tabsChangeNotifier.value;
       });
    });
    }
  }


class NavBarObserver extends NavigatorObserver {
  final ValueNotifier<Tabs> tabsChangeNotifier;

  NavBarObserver(this.tabsChangeNotifier);

  @override
  void didPop(Route route, Route previousRoute) {
    final navBarRoutes = Routes.all.sublist(0,4);
    final routeName = route.settings.name;
    if (navBarRoutes.contains(routeName)) {
      tabsChangeNotifier.value = Tabs.two;
      // selectedIndex = index;
    }
  }
}

暂无
暂无

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

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