Created
July 22, 2020 19:02
-
-
Save dhruvilp/6c15fa1116946c6a80db4899b2792434 to your computer and use it in GitHub Desktop.
RouteObserver
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData(), | |
navigatorObservers: [MyRouteObserver()], | |
home: Screen1(), | |
routes: { | |
'/screen1': (context) => Screen1(), | |
'/screen2': (context) => Screen2(), | |
'/screen3': (context) => Screen3(), | |
}, | |
); | |
} | |
} | |
class MyRouteObserver extends RouteObserver<PageRoute<dynamic>> { | |
void _sendScreenView(PageRoute<dynamic> route) { | |
var screenName = route.settings.name; | |
print('screenName $screenName'); | |
// do something with it, ie. send it to your analytics service collector | |
} | |
@override | |
void didPush(Route<dynamic> route, Route<dynamic> previousRoute) { | |
super.didPush(route, previousRoute); | |
if (route is PageRoute) { | |
_sendScreenView(route); | |
} | |
} | |
@override | |
void didReplace({Route<dynamic> newRoute, Route<dynamic> oldRoute}) { | |
super.didReplace(newRoute: newRoute, oldRoute: oldRoute); | |
if (newRoute is PageRoute) { | |
_sendScreenView(newRoute); | |
} | |
} | |
@override | |
void didPop(Route<dynamic> route, Route<dynamic> previousRoute) { | |
super.didPop(route, previousRoute); | |
if (previousRoute is PageRoute && route is PageRoute) { | |
_sendScreenView(previousRoute); | |
} | |
} | |
} | |
class Screen1 extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Center( | |
child: RaisedButton( | |
color: Colors.pink.shade200, | |
child: Text('GOTO Screen 2'), | |
onPressed: () => Navigator.of(context).pushNamed('/screen2'), | |
), | |
), | |
); | |
} | |
} | |
class Screen2 extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Center( | |
child: RaisedButton( | |
color: Colors.blue.shade200, | |
child: Text('GOTO Screen 3'), | |
onPressed: () => Navigator.of(context).pushNamed('/screen3'), | |
), | |
), | |
); | |
} | |
} | |
class Screen3 extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Center( | |
child: RaisedButton( | |
color: Colors.yellow.shade200, | |
child: Text('GOTO Screen 1'), | |
onPressed: () => Navigator.of(context).pushNamed('/screen1'), | |
), | |
), | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment