Flutter 利用路由监听页面的展示与否
1、新建routeObser.dart文件:
import 'package:flutter/material.dart'; class AppRouteObserver { //这是实际上的路由监听器 static final RouteObserver<ModalRoute<void>> _routeObserver = RouteObserver<ModalRoute<void>>(); //这是个单例 static final AppRouteObserver _appRouteObserver = AppRouteObserver._internal(); AppRouteObserver._internal(); //通过单例的get方法轻松获取路由监听器 RouteObserver<ModalRoute<void>> get routeObserver { return _routeObserver; } factory AppRouteObserver() { return _appRouteObserver; } }
2、修改main.dart如下:
...
MaterialApp(
...,
navigatorObservers: [AppRouteObserver().routeObserver],
);
...
3、监听页面显隐的页面
class _XXX extends State<XXX> with RouteAware { ... @override void didChangeDependencies() { // TODO: implement didChangeDependencies super.didChangeDependencies(); /// 路由订阅 AppRouteObserver().routeObserver.subscribe(this, ModalRoute.of(context)!); } @override void dispose() { // TODO: implement dispose /// 取消路由订阅 AppRouteObserver().routeObserver.unsubscribe(this); super.dispose(); } @override void didPush() { print('跳转该页面而显示'); } @override void didPop() { print('当前页面被pop而隐藏'); } @override void didPopNext() { print('上一个页面关闭而显示'); } @override void didPushNext() { print('跳转下一个页面而隐藏'); } ... }