preface

Android developers should know that Google has come up with a framework for managing the lifecycle, which can be detailed here. Is there a library like this in Flutter? The author looked for quite a long time did not find, if have the reader trouble that knows informs.

Finally, I analyzed the implementation principle of Flutter on Android and wrote a version of Flutter with some changes in details. The project address is flib_lifecycle.

Here’s how to leverage this project for lifecycle management.

How to distribute

  1. Start by writing a LifecycleState for the distribution lifecycle as follows:
abstract class LifecycleState<T extends StatefulWidget> extends State<T> implements FLifecycleOwner {
  final FLifecycleRegistry _lifecycleRegistry = SimpleLifecycleRegistry();
  
  @override
  FLifecycle getLifecycle() {
    return _lifecycleRegistry;
  }

  @override
  void initState() {
    super.initState();
    // Distribute the [flifecycleEvent.onCreate] event
    _lifecycleRegistry.handleLifecycleEvent(FLifecycleEvent.onCreate);
  }

  @override
  void dispose() {
    / / distribution/FLifecycleEvent. OnDestroy events
    _lifecycleRegistry.handleLifecycleEvent(FLifecycleEvent.onDestroy);
    super.dispose(); }}Copy the code

The way the distribution event is written in the code above can also be written to mark a state, and also to notify the lifecycle event to the observer

// Distribute events
_lifecycleRegistry.handleLifecycleEvent(FLifecycleEvent.XXX);

// indicate a certain state
_lifecycleRegistry.markState(FLifecycleState.XXX);
Copy the code
  1. Inherit LifecycleState as follows:
class _DemoPageState extends LifecycleState<DemoPage> {
  @override
  void initState() {
    super.initState();
    // Add an observer
    getLifecycle().addObserver(_lifecycleListener);
  }

  void _lifecycleListener(FLifecycleEvent event, FLifecycle lifecycle) {
    print('_lifecycleListener: ' + event.toString());
  }

  @override
  Widget build(BuildContext context) {
    returnContainer( color: Colors.white, ); }}Copy the code

After running, open this interface, and then close the interface, the console log is as follows:

I/flutter (26755): _lifecycleListener: FLifecycleEvent.onCreate
I/flutter (26755): _lifecycleListener: FLifecycleEvent.onDestroy
Copy the code

More lifecycle events

On Android, activities have more lifecycle events, such as onStart(), onResume(), onPause(), onStop(), and so on. Does the State in Flutter have life-cycle events as detailed as those in Android? Unfortunately, it’s not as detailed as it is in Android, but you can try.

In my opinion, there should be at least the following states and life cycles:

/// Life cycle state
enum FLifecycleState {
  /// Destroy state
  destroyed,
  /// Initialization status
  initialized,
  // create state
  created,
  /// Active status
  started,
}

/// Lifecycle events
enum FLifecycleEvent {
  /// Is in the [flifecycleState.created] state after the event is distributed
  onCreate,
  /// Is in the [flifecycleState. started] state after the event is distributed
  onStart,
  /// Is in the [flifecycleState.created] state after the event is distributed
  onStop,
  / / / distribution in [FLifecycleState. Destroyed] state after the event
  onDestroy,
}
Copy the code

With the above states, it is convenient for the subsequent implementation of more functions, such as stop timer in the created state, restart timer in the active state and so on. How should the State in a FLUTTER distribute onStart and onStop events? The author’s current implementation scheme is as follows:

  1. Write an adapter that distributes the lifecycle of State as follows:
class FStateLifecycleAdapter implements FLifecycleOwner._StateLifecycle {
  final FLifecycleRegistry _lifecycleRegistry;
  bool _started;
  bool _startedMarker;

  FStateLifecycleAdapter({FLifecycleRegistry lifecycleRegistry})
      : this._lifecycleRegistry = lifecycleRegistry ?? SimpleLifecycleRegistry();

  @override
  FLifecycle getLifecycle() {
    return _lifecycleRegistry;
  }

  @override
  void initState() {
    _lifecycleRegistry.handleLifecycleEvent(FLifecycleEvent.onCreate);
  }

  @override
  Widget build(BuildContext context) {
    if (_startedMarker == null) {
      _startedMarker = true;
    }

    if (_startedMarker) {
      _startedMarker = false;
      _started = true;
      _lifecycleRegistry.handleLifecycleEvent(FLifecycleEvent.onStart);
    }

    return null;
  }

  @override
  void deactivate() {
    assert(_startedMarker == false);

    final boolexpected = ! _started;if (expected) {
      _startedMarker = true;
      / / wait for the build
    } else {
      _started = false; _lifecycleRegistry.handleLifecycleEvent(FLifecycleEvent.onStop); }}@override
  void dispose() {
    _started = null;
    _startedMarker = null; _lifecycleRegistry.handleLifecycleEvent(FLifecycleEvent.onDestroy); }}abstract class _StateLifecycle {
  void initState();

  Widget build(BuildContext context);

  void deactivate();

  void dispose();
}
Copy the code
  1. Use the adapter to modify LifecycleState as follows:
abstract class LifecycleState<T extends StatefulWidget> extends State<T> implements FLifecycleOwner {
  final FStateLifecycleAdapter _stateLifecycleAdapter = FStateLifecycleAdapter();

  @override
  FLifecycle getLifecycle() {
    return _stateLifecycleAdapter.getLifecycle();
  }

  @override
  void initState() {
    super.initState();
    _stateLifecycleAdapter.initState();
  }

  @override
  void deactivate() {
    super.deactivate();
    _stateLifecycleAdapter.deactivate();
  }
  
  @override
  Widget build(BuildContext context) {
    _stateLifecycleAdapter.build(context);
    return buildImpl(context);
  }
  
  /// A buildImpl method is used to return widgets because it requires the build method.
  Widget buildImpl(BuildContext context);

  @override
  void dispose() {
    _stateLifecycleAdapter.dispose();
    super.dispose(); }}Copy the code
  1. Inherit the transformed LifecycleState as follows:
class _DemoPageState extends LifecycleState<DemoPage> {
  @override
  void initState() {
    super.initState();
    getLifecycle().addObserver(_lifecycleListener);
  }

  void _lifecycleListener(FLifecycleEvent event, FLifecycle lifecycle) {
    print('_lifecycleListener: ' + event.toString());
  }

  @override
  Widget buildImpl(BuildContext context) {
    return Container(
      color: Colors.white,
      child: GestureDetector(
        child: Text('open the MainPage'),
        onTap: () {
          Navigator.of(context).pushNamed('MainPage'); },),); }}Copy the code

The log is as follows:

  1. Open the DemoPage
I/flutter (26755): _lifecycleListener: FLifecycleEvent.onCreate
I/flutter (26755): _lifecycleListener: FLifecycleEvent.onStart
Copy the code
  1. Jump to the MainPage
I/flutter (26755): _lifecycleListener: FLifecycleEvent.onStop
Copy the code
  1. Close the MainPage
I/flutter (26755): _lifecycleListener: FLifecycleEvent.onStart
Copy the code
  1. Close the DemoPage
I/flutter (26755): _lifecycleListener: FLifecycleEvent.onStop
I/flutter (26755): _lifecycleListener: FLifecycleEvent.onDestroy
Copy the code

Later, we can realize more functions through life cycle monitoring. For example, LiveData in Android can set the change of the observer’s listening value, and automatically release the observer after the life cycle distribution destruction event.

The author of the LiveData version of Flutter has already written about it. If you are interested in it, there will be an article on how to use it later.

conclusion

There is not much introduction to the original life cycle of State in FLUTTER. If readers need to know more about flutter, they can search for it. There are many related articles.

Since the author is also new to Flutter, there is still a lot to learn. If there are any mistakes in the article, please help to correct them.

If you have any questions or need to discuss this library, please feel free to contact me. E-mail: 565061763 @qq.com