Flutter 如何监听当前页面 push显示/消失 pop消失/显示
关键字 MaterialApp
navigatorObservers
Flutter的StatefulWidget
StatelessWidget
生命周期中没有组件出现或者消失的回调,主要是要靠路由的监听
- 创建一个路由监听
final RouteObserver<ModalRoute<void>> _routeObserver =
RouteObserver<ModalRoute<void>>();
- 这里封装了一个单例,方便在各个页面里获取这个路由监听
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;
}
}
- 添加到
MaterialApp
的navigatorObservers
中
MaterialApp(
.....
navigatorObservers: [
AppRouteObserver().routeObserver
],
...)
- 需要监听的页面进行订阅
with RouteAware
class _xxxPageState 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();
}
/// Called when the current route has been pushed.
/// 当前的页面被push显示到用户面前 viewWillAppear.
@override
void didPush() { }
/// Called when the current route has been popped off.
/// 当前的页面被pop viewWillDisappear.
@override
void didPop() { }
/// Called when the top route has been popped off, and the current route
/// shows up.
/// 上面的页面被pop后当前页面被显示时 viewWillAppear.
@override
void didPopNext() { }
/// Called when a new route has been pushed, and the current route is no
/// longer visible.
/// 从当前页面push到另一个页面 viewWillDisappear.
@override
void didPushNext() { }