Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 315
Balaji Avatar asked Oct 14 '25 05:10

Balaji


1 Answers

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.

like image 97
merfire Avatar answered Oct 16 '25 23:10

merfire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!