Dart/Flutter - 从回调函数中yield

5

我需要调用一个不返回任何东西(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

解决方案

创建一个返回未来并使回调函数存储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;
}
1个回答

7
你需要创建其他的事件,并在你的回调函数dispatch事件,然后你可以在过滤你的事件的函数中做你想做的事情。
我不知道你的BLoC的目的是什么,但这个事件的名称取决于用例,它可以是UpdateFormUpdateStateLoggedInLoggedOut等。你会找到最能描述你用例的名称。
记住,你也可以创建带参数的事件,例如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);
}


这是一个不错的解决方案,我通过包装我的store.dispatch函数来解决它,该函数返回一个Future,等待该Future后,我能够在其后yield。 - Mehul Prajapati
2
在flutter_bloc v1.0.0或更高版本中,您应该使用add()方法而不是dispatch()方法。 - miso01

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接