flutter - 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
?
解决方案
这是因为LoginFromSignup
不是 的子类型LoginSubmitted
。
您可以将_onSubmitted
函数更改为接受 a LoginEvent
,即 (LoginFromSignup
和LoginSubmitted
) 都扩展并且是其子类型的类。
像这样:
void _onSubmitted(LoginEvent event, Emitter<LoginState> emit)
推荐阅读
- mobile - 将大型复杂的 3D 场景带入移动设备,请帮助我们提出您的想法![没有限制]
- swift - 将collectionView连接到tableView
- javascript - 点赞按钮怎么实现?
- javascript - Html 视频标签控件在 Firefox 中不起作用
- django - 在 django 模型中获取多对多文件以及模型字段
- rust - TcpStream 在 read_to_string 上被阻止
- c# - 如何将 Formregion 上的 TextBox 绑定到自定义属性?
- c# - 如何在 c# 中查找数据类型/对象/集合“var”存储的内容
- r - 如何在使用 for 循环中使用 dplyr 在 R 中迭代地赋值?
- android - 未能应用颤振插件类“颤振插件”