繁体   English   中英

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

[英]Dart/Flutter - yield from callback function

我需要进行一个不返回任何内容的函数调用( void )。 获得有关函数完成通知的唯一方法是发送callback函数。
现在我将BLoC模式与ReDux一起使用,当一个事件被调度时,我将另一个动作调度到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

解决方案

创建一个返回未来的函数并制作回调函数来存储调度,这里是示例。

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;
}

您需要创建其他event ,并在您的callback函数中dispatchevent ,然后您可以在过滤events的函数中执行您想要的操作。

我不知道您的 BLoC 的目的是什么,但此event的名称取决于用例,可以是UpdateFormUpdateStateLoggedInLoggedOut等。您会找到最适合您的用例的描述性名称。

请记住,您还可以使用参数创建此event ,例如UpdateForm (bool isLoggedIn) ,并根据您的条件yield不同的states

例如,此event的名称是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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM