我需要调用一个不返回任何东西(void
)的函数。唯一得知函数完成的方法是发送一个callback
函数。
现在我正在使用BLoC
模式和ReDux
,当事件被分派时,我会将另一个操作分派到redux
存储中。在action
完成后,它调用callback
函数。现在,在callback
函数内部,我想要更新bloc
的state
。以下是我的实现:
if (event is Login) {
yield currentState.copyWith(formProcessing: true);
store.dispatch(authActions.login(
currentState.username,
currentState.password,
(error, data) {
print(error);
print(data);
// I want to yield here.
yield currentState.copyWith(formProcessing: false);
},
));
}
如上所示的代码片段中,在回调函数中,我想要yield
。
解决方案
创建一个返回未来并使回调函数存储dispatch的函数,这是一个示例。
if (event is Login) {
yield currentState.copyWith(formProcessing: true);
try {
dynamic result = await loginAction(store, currentState.username, currentState.password);
print(result);
yield currentState.copyWith(formProcessing: false);
} catch (e) {
print(e);
}
}
Future loginAction(store, username, password) {
var completer = new Completer();
store.dispatch(authActions.login(
username,
password,
(error, data) {
if (error != null) {
completer.completeError(error);
} else if (data != null) {
completer.complete(data);
}
},
));
return completer.future;
}
add()
方法而不是dispatch()
方法。 - miso01