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(); } /// 当前的页面被push显示到用户面前 viewWillAppear. @override void didPush() { print('显示'); } /// 当前的页面被pop @override void didPop() { print('didPop'); } /// 上面的页面被pop后当前页面被显示时 @override void didPopNext() { print('didPopNext'); } /// 从当前页面push到另一个页面 @override void didPushNext() { print('隐藏'); } ... }
标签:void,监听,routeObserver,AppRouteObserver,override,Flutter,路由,页面 From: https://www.cnblogs.com/atao24/p/17859817.html