本文介绍了在Flutter中使用BLoC进行异步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下载数据,但还要一直使用该应用程序.

I would like download the data, but also use the application all the time.

您能告诉我解决方案是否正确吗?

Can you tell me if it's right solution?

这种情况是我们按下按钮下载并调用函数bloc.dispatch(Event.download());

The case is we press button download and call funtion bloc.dispatch(Event.download());

在_Download事件的mapEventToState中,我们需要数据.但是我们不等待响应,因为我们不想阻止其他正在改变视图的事件.

In mapEventToState in _Download event we reqest data. But we don't wait for response because we don't want to block others events which are changing view.

因此,我创建Future,并在获得响应后调用事件_UpdateData(),在其中处理下载的数据并生成状态.

So I create Future and after getting response I call event _UpdateData() where I process downloaded data and generate state with them.

可以吗?有_requestTime参数可以检查它是否是最后一个请求.

It's ok?There is _requestTime parameter to check if it's last request.

class Bloc {
  DateTime _requestTime;

  @override
  Stream<State> mapEventToState(Event event) async* {
    if (event is _Download) {
      yield DownloadingState();
      _request();
    } else if (event is _UpdateData) {
      if(!event.requestTime.isBefore(_requestTime))
        yield DownladedState(event.response);
    }
  }

  _request() {
    _requestTime = DateTime.now();
    repository.downloadData().then((response) {
      dispatch(_UpdateData(response));
    });
  }
}

推荐答案

让我知道它是否有效

在_request前面的增产**

Changeadded yield* in front of _request

@override
Stream<State> mapEventToState(Event event) async* {
if (event is _Download) {
  yield DownloadingState();
 yield* _request();
} else if (event is _UpdateData) {
  if(!event.requestTime.isBefore(_requestTime))
    yield DownladedState(event.response);
}
}

_request() async*{
_requestTime = DateTime.now();
repository.downloadData().then((response) {
  dispatch(_UpdateData(response));
});
}
}

这篇关于在Flutter中使用BLoC进行异步请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 23:40