场景
我的flutter app使用auto_route库管理路由,我的tab会开启轮询,需要监听当前tab的离开事件来关闭轮询。
背景
auto_route 库6.0.5版本(当前版本)不支持在嵌套路由中使用AutoRouteGuard 路由守卫,导致无法使用守卫控制tab切换流程;
解决方案
使用当前tab initState 过程中的context.tabsRouter ,为其addListener 监听tab变化,利用tab路由的activeIndex 和previousIndex 判断处理,顺利解决问题。
void initState() {
debugPrint("initState");
super.initState();
context.tabsRouter.addListener(currentTabListener);
}
void currentTabListener() {
if (context.tabsRouter.activeIndex != TARGET_INDEX && context.tabsRouter.previousIndex == TARGET_INDEX) {
// do something
debugPrint("-----> tab leave");
} else if (context.tabsRouter.activeIndex == TARGET_INDEX) {
debugPrint("-----> tab in");
// do something
}
}
void dispose() {
super.dispose();
context.tabsRouter.removeListener(currentTabListener);
}