flutter
Can monitorapp
Enter the front desk or backend state, you can also listen to a certain page.Currently displaying
stillHide
。-
Find a public file to initialize it
Router Observer
,For example:, as long as it can be made into a global object.
///Route observerfinal routeObserver = RouteObserver<PageRoute>();
Have itRouter Observer
After the object is registered as the navigation listener:
/// MaterialApp Widget buildMaterialApp(BuildContext context) { // Here you directly register globally in the MaterialApp object, and there are other modes, such as CupertinoApp, WidgetsAp, Navigator return GetMaterialApp( title: 'Flutter Demo', // register navigatorObservers: [routeObserver], ); ... ... ... } }
Use the page, it is recommended to encapsulate as the underlying layerBaseStateful
Use, other pages inherit, can be opened at any time, or can be used on a single page:
import 'package:flutter/'; import 'package:base_project/utils/'; @immutable class BaseStatefulController extends StatefulWidget { const BaseStatefulController({}); @override State<BaseStatefulController> createState() => BaseStatefulControllerState(); } class BaseStatefulControllerState extends State<BaseStatefulController> with RouteAware { /// Enable routing observer bool enableRouteObserver = false; @override void initState() { (); // Wait for loading ((_) { // Initialization context complete initStateContext(); }); } /// Initialization context is completed, you can do some initialization operations that require context here. void initStateContext () { // Register the route monitoring if (enableRouteObserver) { final route = (context); if (route is PageRoute) { (this, route); } } } @override void dispose() { // Cancel the routing monitoring (this); (); } @override void didPush() { print("The page is pushed to the top of the stack, and the page is visible"); } @override void didPop() { print("The page is popped, the page is destroyed"); } @override void didPushNext() { print("A new page push comes in, the current page enters an invisible state"); } @override void didPopNext() { print("The previous page was popped, the current page is revisited"); } @override Widget build(BuildContext context) { return Container(); } }
method | effect |
---|---|
subscribe(routeAware, route) |
Subscribe to a page to monitor life cycle changes |
unsubscribe(routeAware) |
Unsubscribe to avoid memory leaks |
didPush() |
The page is visible |
didPop() |
Page destruction |
didPushNext() |
The current page is overwritten and not visible |
didPopNext() |
The previous page waspop , the current page is visible again |
The above is the detailed explanation of the code for Flutter monitoring the current page that is visible and hidden. For more information about Flutter monitoring the current page, please follow my other related articles!