Android中的Activity的生命週期方法以下所示:android
這些方法中,對咱們比較重要的以下:git
在使用過程當中,onCreate和onDestroy方法成對出現,只會調用一次。onResume和onPause方法也是成對出現,會出現屢次。github
這幾個方法爲什麼如此重要呢?爲何非要在flutter端獲取到這幾個方法呢? 這是由於在現有條件下,flutter相關的社區環境還不夠強大,flutter端並不能實現一套代碼適配多種終端的效果,相反,它還會嚴重的依賴宿主App端的實現。bash
這時,就須要咱們在flutter頁面中合適的時機,發送消息給宿主App,讓其完成對應的實現。app
固然了,這類問題在之後可能會獲得很好的解決,沒必要像如今這麼費勁。less
一、桌面 --> home --> a --> c --> a --> home --> 桌面ide
對應log:ui
I/flutter ( 1954): Home --> onCreate()
I/flutter ( 1954): Home --> onResume()
I/flutter ( 1954): ARoute --> onCreate()
I/flutter ( 1954): ARoute --> onResume()
I/flutter ( 1954): Home --> onPause()
I/flutter ( 1954): CRoute --> onCreate()
I/flutter ( 1954): CRoute --> onResume()
I/flutter ( 1954): ARoute --> onPause()
I/flutter ( 1954): ARoute --> onResume()
I/flutter ( 1954): CRoute --> onPause()
I/flutter ( 1954): CRoute --> onDestroy()
I/flutter ( 1954): Home --> onResume()
I/flutter ( 1954): ARoute --> onPause()
I/flutter ( 1954): ARoute --> onDestroy()
I/flutter ( 1954): Home --> onPause()
複製代碼
這裏解釋下: 桌面 --> home操做對應log: 一、2行 home --> a操做對應log: 三、四、5行 a --> c操做對應log: 六、七、8行 c --> a操做對應log: 九、十、11行 a --> home操做對應log: 十二、1三、14行 home --> 桌面操做對應log: 15行spa
二、桌面 --> home --> b --> e --> b --> home --> 桌面code
對應log:
I/flutter ( 2048): Home --> onCreate()
I/flutter ( 2048): Home --> onResume()
I/flutter ( 2048): BRoute --> onCreate()
I/flutter ( 2048): BRoute --> onResume()
I/flutter ( 2048): Home --> onPause()
I/flutter ( 2048): FRoute --> onCreate()
I/flutter ( 2048): FRoute --> onResume()
I/flutter ( 2048): BRoute --> onPause()
I/flutter ( 2048): BRoute --> onResume()
I/flutter ( 2048): FRoute --> onPause()
I/flutter ( 2048): FRoute --> onDestroy()
I/flutter ( 2048): Home --> onResume()
I/flutter ( 2048): BRoute --> onPause()
I/flutter ( 2048): BRoute --> onDestroy()
I/flutter ( 2048): Home --> onPause()
複製代碼
這裏解釋下: 桌面 --> home操做對應log: 一、2行 home --> b操做對應log: 三、四、5行 b --> e操做對應log: 六、七、8行 e --> b操做對應log: 九、十、11行 b --> home操做對應log: 十二、1三、14行 home --> 桌面操做對應log: 15行
在pubspec.yaml文件中添加以下依賴:這裏選擇最新版本便可。
dependencies:
flutter_lifecycle_state: ^0.0.x
複製代碼
note:最新配置請看pub.dartlang.org/packages/fl…頁面。
這個值定義在咱們的package包中,須要導包。
import 'package:flutter/material.dart';
import 'package:flutter_lifecycle_state/flutter_lifecycle_state.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
...
navigatorObservers: [routeObserver],
);
}
}
複製代碼
將每一個頁面級別的Widget的State替換爲咱們的StateWithLifecycle,導包便可。而後咱們能夠選擇重寫onCreate、onPause、onResume、onDestroy方法,在這些方法內部執行對應的業務邏輯便可。
若是須要自定義當前頁面的log標識的話,以下所示:給tagInStateWithLifecycle
字段賦值便可。
@override
void initState() {
tagInStateWithLifecycle = "WidgetsTestPage";
super.initState();
}
複製代碼
須要注意的是:
一、onDestroy方法某些狀況下不會調用
在flutter項目的根頁面中,在它正常銷燬時,它的的dispose方法是不會調用的,所以咱們的onDestroy方法也不會調用。
二、應用非正常關閉時,生命週期方法不會調用。
這就意味着,若是應用在後臺被回收,或者其餘方式非正常關閉,則某些頁面的生命週期方法可能不會正常的調用。