如何在使用auto_route包的flutter应用程序中重新启动TabPage的构建方法



嗨,在flutter应用程序中使用auto_route包。如何在TabPage上重新启动构建方法或切换选项卡时不保存堆栈状态。我应该有一个动画运行在构建方法上的TabPage每次我切换一个选项卡在导航栏。但是,当我单击导航栏

中的按钮时,不会调用构建方法。

在你的@MaterialAutoRouter()中添加这个属性到你想在每次用户点击项目时重建的选项卡栏子属性:

AutoRoute(path: 'your_path', page: YourPage, maintainState: false), //<- with this the tab will rebuild every time.

如果你想对动作有更多的控制,并且你有一个嵌套的路由,你可以添加一个监听器

class _YourWidgetState extends State<YourWidget> with AutoRouteAware{ // <- add this
AutoRouteObserver? _observer;
@override
void didChangeDependencies() {
super.didChangeDependencies();
_observer = RouterScope.of(context).firstObserverOfType<AutoRouteObserver>();
if (_observer != null) {
_observer?.subscribe(this, context.router.currentChild!);
}
context.tabsRouter.addListener(() {
if (context.tabsRouter.activeIndex == 1) { //your tab index here
// DO WHATEVER YOU WANT
}
});
}

如果选项卡router没有嵌套到一个空的routerpage中,只需使用AutoRouteAwareStateMixin进行扩展。

class _YourWidgetState extends State<YourWidget> with AutoRouteAwareStateMixin<YourWidget> { // <- add this
void didInitTabRoute(TabPageRoute? previousRoute) async {
//do something on first tap
}
void didChangeTabRoute(TabPageRoute previousRoute) async {
//do something on successives taps
}

我猜你就是评论我文章的那个用户。我在这里给出相同的答案。这与autoroute包本身无关,但它是底部栏导航的默认行为。我们的目标是尽量减少UI所需的重构次数。

我没有测试它,但你可以尝试使你的选项卡一个有状态的小部件(如果它还没有),并修改此行为与AutomaticKeepAliveClientMixin<YourWidget>:

class _YourWidgetState extends State<YourWidget> with AutomaticKeepAliveClientMixin<YourWidget>{
// Here you build your Widget after calling the super method
@override Widget build(BuildContext context) { 
super.build(context) 
return Container(); 
} 
// the important part is returning false here
@override bool get wantKeepAlive => false; 
}

相关内容

最新更新