首页 > 解决方案 > 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?

标签: flutterdartflutter-bloc

解决方案


这是因为LoginFromSignup不是 的子类型LoginSubmitted

您可以将_onSubmitted函数更改为接受 a LoginEvent,即 (LoginFromSignupLoginSubmitted) 都扩展并且是其子类型的类。

像这样:

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

推荐阅读