gpt4 book ai didi

redux - Dart/Flutter - 从回调函数中产生

转载 作者:IT王子 更新时间:2023-10-29 07:16:51 26 4
gpt4 key购买 nike

我需要进行一个不返回任何内容的函数调用 (void)。获得函数完成通知的唯一方法是发送一个回调函数。
现在我使用 BLoC 模式和 ReDux,当一个事件被分派(dispatch)时,我分派(dispatch)另一个 Action 到 redux 的存储,在 之后action 完成后调用 callback 函数。现在在 callback 函数中,我想更新 blocstate。下面是我的实现,

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

解决方案

创建一个返回 future 的函数,并创建回调函数来存储分派(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;
}

最佳答案

您需要创建其他事件,并在您的回调函数中调度这个事件,然后您可以在过滤事件的函数中做你想做的事。

我不知道你的 BLoC 的目的是什么,但是这个 event 的名称取决于用例,它可以是 UpdateForm, UpdateStateLoggedInLoggedOut 等。您会为您的用例找到最具描述性的名称。

请记住,您还可以使用参数创建此事件,例如UpdateForm (bool isLoggedIn),以及yield不同的状态 根据您的条件。

例如,这个事件的名称是OtherEvent

if (event is Login) {
yield currentState.copyWith(formProcessing: true);
store.dispatch(authActions.login(
currentState.username,
currentState.password,
(error, data) {
print(error);
print(data);

dispatch(OtherEvent());
},
));
} else if (event is OtherEvent) {
// You can yield here what you want
yield currentState.copyWith(formProcessing: false);
}

关于redux - Dart/Flutter - 从回调函数中产生,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57106401/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com