Search code examples
flutterstatescoped-model

How to manage multi page form state with scoped model in flutter


I have a multi page form that I need to manage state with. I am currently trying to use the scoped model but it's not working. Everything I go to another page the state is cleared. I'm usually the PageView widget to create the multi page form. What I really what do know is why the state is not persisting. Thank you


Solution

  • You want to make sure your ScopedModel is correctly wrapping all of the pages in your multi page form. Often, you want to wrap your entire app with your ScopedModel. Something like this:

    Future startUp() async {
      UserModel userModel = await loadUser();
      runApp(ScopedModel<UserModel>(model: userModel, child: MyApp()));
    }
    
    void main() {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
      startUp();
    }
    

    In some situations, you want to rebuild whenever the Model changes (users logs in?)
    Example:

      @override
      Widget build(BuildContext context) {
        return ScopedModelDescendant<UserModel>(
            builder: (BuildContext context, Widget child, UserModel model) {
          return Scaffold(
              body: ListView(
                children: <Widget>[
                  // your page here
                ]
              )
          );
        });
      }