1

I am trying out async_redux for Flutter and like the idea with nested states.

I have a AppState like this:

class AppState {
  final LoginState loginState;

  AppState({this.loginState});

  AppState copy({LoginState loginState}) {
    return AppState(
      loginState: loginState ?? this.loginState,
    );
  }

...

And my LoginState:

class LoginState {
  final bool isLoggedIn;

  LoginState({this.isLoggedIn});

  LoginState copy({bool isLoggedIn}) {
    return LoginState(isLoggedIn: isLoggedIn ?? this.isLoggedIn);
  }

...

But how do I make my reducer update the isLoggedIn in my LoginState? I have tried a few things, but not getting anywhere. This obvious isnt working, but just to give a starting point:

class LoginAction extends ReduxAction {

  final String username;
  final String password;

  LoginAction({this.username, this.password}) : assert(username != null && password != null);

  @override
  AppState reduce() {
    return state.copy(loginState: state.loginState.isLoggedIn = true);
  }
}

Any ideas?

Thank you
Søren

Marcelo Glasberg
  • 29,013
  • 23
  • 109
  • 133
Neigaard
  • 3,726
  • 9
  • 49
  • 85

1 Answers1

1

The login process is async, so you should probably do Future<AppState> reduce() instead of AppState reduce().

Then you have to run your login code and get back a boolean that states if the user is now logged in or not: bool result = await logIn(username, password);

If it was not successful, throw an user-exception: if (!done) throw UserException("Please check your username and password.");

At this point, recreate the state with the change:

class LoginAction extends ReduxAction {

  final String username;
  final String password;

  LoginAction({this.username, this.password}) :
     assert(username != null && password != null);

  @override
  Future<AppState> reduce() {
    if (state.loginState.isLoggedIn) throw UserException("You are already logged in.");

    bool done = await logIn(username, password);

    if (!done) throw UserException("Please check your username and password.");

    return state.copy(
              loginState: state.loginState.copy(isLoggedIn: true),
    );
  }
}
Marcelo Glasberg
  • 29,013
  • 23
  • 109
  • 133