【发布时间】:2019-11-28 02:10:53
【问题描述】:
我需要进行一个不返回任何内容的函数调用 (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);
},
));
}
如上面代码sn-p所示,在回调函数里面,我要yield。
解决方案
创建一个返回未来的函数,并制作回调函数来存储调度,这里是示例。
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;
}
【问题讨论】: