分两块读取Firebase数据库Flutter

时间:2018-08-18 03:51:04

标签: firebase-realtime-database dart flutter

我正在创建一个Flutter应用程序,该应用程序可以从Firebase数据库中加载大量数据。我的想法是在应用程序最初加载时从数据库加载前20个左右的观察值,然后在应用程序继续运行时继续加载其余数据。

本质上,我想异步加载前20个观察值并返回它们。然后,如果用户在所有数据加载完成之前需要数据,则可以使用它们。随着应用程序的继续,我希望其余数据异步加载并收集到列表中。

到目前为止,这是我想出的解决方案:

Stream<List<Event>> chunkLoad(int firstChunk, String location) {
  StreamController<List<Event>> controller = new StreamController<List<Event>>();

  StreamSubscription<Event> subscription;
  List<Event> chunkedOutput = [];
  DatabaseReference ref = database.reference().child(location);

  void startSubscription(){
    subscription = ref.onValue.listen((Event event){
      chunkedOutput.add(event);
      if (chunkedOutput.length == firstChunk)
        controller.add(chunkedOutput);
    });
    subscription.onDone((){
      controller.add(chunkedOutput);
      controller.close();
    });
  }

  void endSubscription(){
    subscription.cancel();
    subscription = null;
  }

  void pauseSubscription(){subscription.pause();}
  void resumeSubscription(){subscription.resume();}

  controller = new StreamController<List<String>>(
    onListen: startSubscription,
    onCancel: endSubscription,
    onPause: pauseSubscription,
    onResume: resumeSubscription,
  );
  return controller.stream;
}

此方法旨在预订onValue个事件,并将其中的第一个firstChunk作为流中的第一个值返回,然后将所有接收到的事件作为第二个和最终值从流中返回流。但是,我不确定如何使用这种方法来完成我想要做的事情。

同样,我想监听此流中的第一个事件并正常处理,同时还要监听此流中的最后一个事件并将结果放入静态列表中。这可能吗?任何帮助将不胜感激。

0 个答案:

没有答案
相关问题