Flutter开发之——监听堆栈变化
在Flutter中,可以使用Navigator的overlay
属性来监听堆栈的变化。以下是一个简单的例子,展示如何使用Navigator
的observer
来监听路由堆栈的变化:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
navigatorObservers: [MyNavigatorObserver()],
);
}
}
class HomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextButton(
child: Text('Push Page'),
onPressed: () => Navigator.push(context, MaterialPageRoute(builder: (context) => Page())),
),
),
);
}
}
class Page extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: TextButton(
child: Text('Pop'),
onPressed: () => Navigator.pop(context),
),
),
);
}
}
class MyNavigatorObserver extends NavigatorObserver {
@override
void didPush(Route route, Route previousRoute) {
print('Did push route: $route');
}
@override
void didPop(Route route, Route previousRoute) {
print('Did pop route: $route');
}
@override
void didRemove(Route route, Route previousRoute) {
print('Did remove route: $route');
}
@override
void didStartUserGesture(Route route, Route previousRoute) {
print('Did start user gesture on route: $route');
}
@override
void didStopUserGesture() {
print('Did stop user gesture');
}
}
在这个例子中,我们定义了一个MyNavigatorObserver
类,它扩展了NavigatorObserver
并覆盖了相关的方法来监听路由堆栈的变化。然后,我们在MaterialApp
中通过navigatorObservers
属性将它添加到应用中。当路由堆栈发生变化时,例如当我们推送或弹出路由时,MyNavigatorObserver
中相应的方法会被调用,并打印出相关的路由信息。
评论已关闭