Flutter 监听页面did appear和did disappear

// 注册 RouteObserver  作为 navigation observer.
final RouteObserver routeObserver = 
  RouteObserver();
  void main() {
runApp(MaterialApp(
home: Container(),
navigatorObservers: [routeObserver],
 ));
   }

 class RouteAwareWidget extends StatefulWidget {
  State createState() => RouteAwareWidgetState();
 }

 // 实现RouteAware抽象类
  class RouteAwareWidgetState extends State with 
 RouteAware {

@override
void didChangeDependencies() {
  super.didChangeDependencies();
// 订阅 routeObserver,之后就会尝试调用抽象类 RouteAware 的方法
routeObserver.subscribe(this, ModalRoute.of(context)); 
}

@override
void dispose() {
routeObserver.unsubscribe(this);
super.dispose();
}

@override
void didPush() {
  // 当前页面入栈
}

 @override
void didPopNext() {
  // 当前路由的下个路由出栈,且当前页面显示
 }

@override
Widget build(BuildContext context) => Container();

 } 

你可能感兴趣的:(Flutter 监听页面did appear和did disappear)