flutterapplication-lifecycle

Flutter: Common class to whole check whole app lifecycle


I wanted to check if my app is in the background or foreground, Therefore the following method will give the state of the App.

@override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.inactive:
        print('appLifeCycleState inactive');
        break;
      case AppLifecycleState.resumed:
        print('appLifeCycleState resumed');
        break;
      case AppLifecycleState.paused:
        print('appLifeCycleState paused');
        break;
      case AppLifecycleState.detached:
        print('appLifeCycleState detached');
        break;
    }
  }

Scenario: I have one task that should perform on Resume/Pause all over the app. As I am having many different screens, It won't be good to implement them separately for every class.

Is there any way to create one common class and extend it to every widget?


Solution

  • Create one file called base_state.dart and paste the following code.

    import 'package:flutter/material.dart';
    
    abstract class BaseState<T extends StatefulWidget> extends State<T>
        with WidgetsBindingObserver {
      @override
      void initState() {
        super.initState();
        WidgetsBinding.instance.addObserver(this);
      }
    
      @override
      void didChangeAppLifecycleState(AppLifecycleState state) {
        super.didChangeAppLifecycleState(state);
        switch (state) {
          case AppLifecycleState.inactive:
            print('appLifeCycleState inactive');
            break;
          case AppLifecycleState.resumed:
            print('appLifeCycleState resumed');
            break;
          case AppLifecycleState.paused:
            print('appLifeCycleState paused');
            break;
          case AppLifecycleState.detached:
            print('appLifeCycleState detached');
            break;
        }
      }
    
      @override
      void dispose() {
        super.dispose();
        WidgetsBinding.instance.removeObserver(this);
      }
    }
    
    

    Now extend your StatefulWidget with BaseState instead of State like this.

    
    class TempPage extends StatefulWidget {
      const TempPage({Key? key}) : super(key: key);
    
      @override
      State<TempPage> createState() => _TempPageState();
    }
    
    class _TempPageState extends BaseState<TempPage> {
      @override
      Widget build(BuildContext context) {
        return Container();
      }
    }