简体   繁体   中英

With Flutter blocs, how do I use two events with the same callback?

I'm using the library flutter_bloc and I have two different events -- one that will accept arguments while the other will not.

class LoginSubmitted extends LoginEvent {
  const LoginSubmitted();
}

class LoginFromSignup extends LoginEvent {
  const LoginFromSignup({
    this.username,
    this.password,
  });

  final String username;
  final String password;

  @override
  List<Object> get props => [username, password];
}

However, these two events will pretty much do the same thing. I am having trouble implementing that in my login_bloc . Ideally I want something like this:

    on<LoginUsernameChanged>(_onUsernameChanged);
    on<LoginPasswordChanged>(_onPasswordChanged);
    on<LoginSubmitted>(_onSubmitted);
    on<LoginFromSignup>(_onSubmitted); <-- this doesn't work

As you can see above, the line on<LoginFromSignup>(_onSubmitted); gives me an error:

The argument type 'void Function(LoginSubmitted, Emitter<LoginState>)' can't be assigned to the parameter type 'FutureOr<void> Function(LoginFromSignup, Emitter<LoginState>)'.

I assume my method definition is off:

void _onSubmitted(
    LoginSubmitted event, <--- this might be problematic
    Emitter<LoginState> emit,
  ) async {

With the example above, the event arg is accepting LoginSubmitted . How do I make it so it accepts both LoginSubmitted and LoginFromSignup ?

This is because LoginFromSignup is not a subtype of LoginSubmitted .

You can change the _onSubmitted function to accept a LoginEvent , the class that both ( LoginFromSignup and LoginSubmitted ) extend and are subtypes of.

Like this:

void _onSubmitted(LoginEvent event, Emitter<LoginState> emit)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM