flutter_lifecycle_state

Make State support lifecycle method just like Android's Activity#onCreate、 Activity#onResume、Activity#onPause、Activity#onDestroy.

Getting Started

1、register observer to app's navigatorObservers。

Code as below:

return MaterialApp(
  title: 'Flutter Demo',
  ...

  // Register the RouteObserver as a navigation observer.
  navigatorObservers: [routeObserver],
);

2、How to use the StateWithLifecycle:

Replace the State of each page-level StatefulWidget with our StateWithLifecycle.

Then we can choose to override onCreate, onPause, onResume, onDestroy method, within these methods can perform the corresponding business logic.

If you need to customize the current page log id, as shown in the following: give tagInStateWithLifecycle field assignment.

class TestRoute extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _TestRouteState();
}

class _TestRouteState extends StateWithLifecycle<TestRoute> {

  @override
  void initState() {
    // You need to set the tag id before the super. InitState () method
    tagInStateWithLifecycle = "_TestRouteState";
    super.initState();
  });
  
  @override
  void onCreate() {
    super.onCreate();
    // todo 
  }
    
  @override
  void onResume() {
    super.onResume();
    // todo
  }
    
  @override
  void onPause() {
    super.onPause();
    // todo
  }
    
  @override
  void onDestroy() {
    super.onDestroy();
    // todo
  }
}

3、Attention:

①The lifecycle method calls for the widgets on the Flutter side are all made by the host app side. The flutter terminal will no longer receive any messages after the application is abruptly closed.

②When the root page on the Flutter side closes properly, the State#dispose method is not raised, so our onDestroy method is not raised, so if you want to free the resource, you'll have to do it yourself.

4、The demo address

https://github.com/tinyvampirepudge/flutter_lifecycle_state_test

中文文档

Libraries

flutter_lifecycle_state