异步未来,如何将已提取单个项目的事件发送回调用方?

时间:2018-12-04 08:05:33

标签: dart flutter

我正在制作一个Future方法,该方法位于单独的类中,该方法可获取一堆XKCD漫画,并将它们放入列表中并返回。

这很好而且很花哨,但是我想在拿到单个漫画时通知我,所以我可以显示进度对话框,显示我们有多远。

这是我的代码:

// This is inside my class ComicManager
Future<List<ComicModel>> generateComicList() async {
  List<ComicModel> comicList = new List<ComicModel>();

  ComicModel latestComic = await getLatestComic();

  for (var i = 1; i <= latestComic.num; i++) {
    try {
      http.Response response =
          await http.get('https://xkcd.com/${i}/info.0.json');

      Map comicmap = json.decode(response.body);
      var comic = new ComicModel.fromJson(comicmap);
      comicList.add(comic);
      print(comic.num);

      // Notify here that we have fetched a comic

    } catch (ex) {
      // Comic could apparently not be parsed, skip it.
    }
  }

  return comicList;
}

我应该如何解决?

2 个答案:

答案 0 :(得分:0)

似乎没有特别优雅的方法可以做到这一点。从一些颤动的代码示例中,似乎可以使用VoidCallBack侦听器。

Set中的第一个注册回调函数

Set<VoidCallBack> listeners

然后定义所需的回调函数。并将它们添加到集合中

void fun()
//...
listeners.add(fun);//Or you can define a method to do this or simply pass the function through the constructor of this class.

最后,编写一个notifyListeners函数或等效函数,然后在任何需要的地方调用

void notifyListeners(){
    for(final listener in listeners){
        listener();
    }
}

如果您希望回调函数带有参数,只需将VoidCallBack更改为任何函数类型即可。

答案 1 :(得分:0)

找到了解决方案。

我只是这样使用Streams

Stream<ComicProgressModel> getAllComicsStream() async* {
  // Do what you need to do here

  // This will respond back when you are listening to the stream
  yield stuffToYield; // Can be anything, and you can yield as many times you want

  // When you reach the end of the method, the onDone method will be called. 
  // So if you are running a for loop, and call yield multiple times it onDone is only called the the this method ends
}

然后我可以听这样的事件:

Stream comicStream =
      ComicManager().getAllComicsStream().asBroadcastStream();

StreamSubscription comicsub = comicStream.listen((onData) {
  // Do what i need
});

说实话超级容易。