Search code examples
flutterdartviewmodelproviderstacked

how to handle state of the app or lifecycle in stacked or provider architecture in flutter


I am using stacked architecture in my project. Here is my code

class InfoScreen extends StatelessWidget {

  InfoViewModel viewModel;

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<InfoViewModel>.reactive(
        builder: (context, model, child) => _buildUI(model),
        viewModelBuilder: () => InfoViewModel());
  }

  _buildUI(InfoViewModel viewModel) {
    return Scaffold(backgroundColor: Colors.white, body: MainScreen());
  }
}

I am using the Stateless widget, So I can't use the didChangeDependencies() method to know the app state.

My Question is How do I handle app state in this screen? any help or idea is appreciated. thanks in advance


Solution

  • You can implement didChangeDependencies() in your ViewModel.

    For example:

    class InfoViewModel extends BaseViewModel with WidgetsBindingObserver{
    
      void initialise() {
        WidgetsBinding.instance.addObserver(this);
      }
    
      @override
      Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
        switch (state) {
          case AppLifecycleState.resumed:
            print('On Resume');
            break;
          case AppLifecycleState.inactive:
          case AppLifecycleState.paused:
          case AppLifecycleState.detached:
            break;
        }
      }
    
      @override
      void dispose() {
        WidgetsBinding.instance.removeObserver(this);
        super.dispose();
      }
    }
    

    Don't forget to call onModelReady: (model) => model.initialise() in your View widget.