1、新建routeMonitor.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();
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() {
super.didChangeDependencies();
AppRouteObserver().routeObserver.subscribe(this, ModalRoute.of(context)!);
}
@override
void dispose() {
AppRouteObserver().routeObserver.unsubscribe(this);
super.dispose();
}
@override
void didPush() {
print('跳转该页面而显示');
}
@override
void didPop() {
print('当前页面被pop而隐藏');
}
@override
void didPopNext() {
print('上一个页面关闭而显示');
}
@override
void didPushNext() {
print('跳转下一个页面而隐藏');
}
...
}