nyphur
nyphur

Reputation: 2896

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?

Upvotes: 0

Views: 872

Answers (1)

pedro pimont
pedro pimont

Reputation: 3084

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)

Upvotes: 1

Related Questions