In the Flutter project, it is necessary to monitor the life cycle of the widget. However, the listening method in the SDK is not very useful. Therefore, a base class of State is extracted to monitor the life cycle of the widget, including the life cycle of the flutter and the life cycle of the widget. We need direct take, see the specific use of notes.

import 'package:flutter/material.dart'; // Create date: 2020/8/14 // /// /// void main() {/// / observers (/// navigatorObservers: [lifeObserver], /// home: FirstWidget(), /// )); Final RouteObserver<Route> lifeObserver = RouteObserver(); // call onResume() if the Widget is visible, onPaused() if the Widget is not visible, onPaused(), /// /// when Apush opens B,A calls onPaused() and B calls onResume(); // when Bpop returns A,A calls onResume() and B calls onPaused(); // onPaused() is called when the screen is locked or the background is backed up; OnResume () is called when moving from background to foreground or unlocking from lock screen; /// /// To use this method, replace State with LifeState. // It is not recommended to perform a large number of time-consuming operations on a callback. Instead, you can do some start/stop flags for scheduled tasks StatefulWidget> extends State<T> with WidgetsBindingObserver, RouteAware { @override void initState() { WidgetsBinding.instance.addObserver(this); super.initState(); } @override void didChangeDependencies() { lifeObserver.subscribe(this, ModalRoute.of(context)); super.didChangeDependencies(); } @override void dispose() { WidgetsBinding.instance.removeObserver(this); lifeObserver.unsubscribe(this); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { if (state == AppLifecycleState.resumed) { onResume(); } else if (state == AppLifecycleState.paused) { onPaused(); } } void didPop() { onPaused(); } void didPopNext() { onResume(); } void didPush() { onResume(); } void didPushNext() { onPaused(); } void onResume(); void onPaused(); }Copy the code

Benefits:

My company is looking for an engineer for Android/Flutter. Bachelor degree, more than 2 years development experience; Salary 10-15, interested parties can talk privately.