其他分享
首页 > 其他分享> > Flutter从其他页面返回到当前页面时的监听

Flutter从其他页面返回到当前页面时的监听

作者:互联网

转自https://blog.csdn.net/sinat_17775997/article/details/106570011

实现支持手势返回回传参数
路由回调
RouteAware×
deactivate××

目录

实现一:路由回调

Navigator.push(context, route).then((res) {
	// do some something
	// res为pop方法回传参数
});

实现二:RouteAware

  1. 在程序入口定义静态变量
    // 用于路由返回监听
    static final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();
    
  2. MaterialApp添加参数
    return MaterialApp(
    	// ...
    	navigatorObservers: [MyApp.routeObserver]
    );
    
  3. 在需要定义的StatefulWidget的State中添加with RouteAware
    class _MyPageStateState extends State<MyPage> with RouteAware{}
    
  4. 添加订阅
    @override
    void didChangeDependencies() {
    	super.didChangeDependencies();
        // 添加监听订阅
    	MyApp.routeObserver.subscribe(this, ModalRoute.of(context));
    }
     
    @override
    	void dispose() {
    	// 移除监听订阅
    	MyApp.routeObserver.unsubscribe(this);
    	super.dispose();
    }
    
  5. 重写监听方法
    @override
    	void didPush() {
    	super.didPush();
    	// push进入当前页面时走这里
    	LogUtils.d('生命周期监听', 'didPush');
    }
    
    @override
    	void didPushNext() {
    	super.didPushNext();
    	// 当前页面push到其他页面走这里
    	LogUtils.d('生命周期监听', 'didPushNext');
    }
    
    @override
    void didPop() {
    	super.didPop();
    	// pop出当前页面时走这里
    	LogUtils.d('生命周期监听', 'didPop');
    }
    
    @override
    void didPopNext() {
    	super.didPopNext();
    	// 从其他页面pop回当前页面走这里
    	LogUtils.d('生命周期监听', 'didPopNext');
    }
    

实现三:重写State的deactivate方法

@override
void deactivate() {
	bool isBack = ModalRoute.of(context).isCurrent;
	if (isBack) {
		// 限于从其他页面返回到当前页面时执行,首次进入当前页面不执行
		// 注:此方法在iOS手势返回时,不执行此处
		logPrint('从其他页面返回到${widget.runtimeType}页');
	} else {
		// 离开当前页面或退出当前页面时执行
		logPrint('离开或退出${widget.runtimeType}页');
	}
	super.deactivate();
}

标签:deactivate,void,Flutter,override,super,监听,页面
来源: https://blog.csdn.net/codecat_yi/article/details/113033046