flutter_super_state icon indicating copy to clipboard operation
flutter_super_state copied to clipboard

Local modules feature maybe?

Open kamiltoszek opened this issue 5 years ago • 1 comments

Modules are singletons created at the beginning - which is ok, but if module is a representation of a form state, I would like to be able to reset form's state on first enter to that form page. In counter example you reset counterModule on logout from authModule, but it's not very maintenance friendly architecture.

kamiltoszek avatar May 12 '20 15:05 kamiltoszek

I've always maintained the idea that local state should be local, and global state should be global.

In other words, I would suggest having the form state inside your widgets. Since the state is only used there, it's a logical place to locate it.

However, the use case you are saying would work. Here's a small example:

class LoginFormModule extends StoreModule {
  var username = "";
  var password = "";

  LoginFormModule(Store store): super(store);

  void setUsername(String username) {
    setState(() {
      this.username = username;
    });
  }

  void setPassword(String password) {
    setState(() {
      this.password = password;
    });
  }

  void reset() {
    setState(() {
      username = "";
      password = "";
    });
  }
}

class LoginScreen extends StatelessWidget {
  LoginScreen() {
    // Would use `after_layout` of post frame callback here, this just a shortcut
    Future(() {
      StoreProvider.store(context).getModule<LoginFormModule>().reset();
    });
  }

  @override
  Widget build(BuildContext context) {
    return ModuleBuilder<LoginFormmodule>(
      builder: (context, loginFormModule) {
        return Column(
          children: <Widget>[
            TextField(
              onChanged: loginFormModule.setUsername,
            ),
            TextField(
              onChanged: loginFormModule.setPassword,
            ),
          ],
        );
      },
    );
  }
}

In this specific use case, since there's no initial value, it would be empty to start anyways.

Cretezy avatar May 12 '20 19:05 Cretezy