我有一个Firestore文档,该文档很少更改,并且在我的应用程序中的许多不同位置用作查找表。据我了解,获取文档时,即使文档中的数据没有更改,它也总是在执行服务器查询。仅当服务器不可用时才使用本地缓存。
由于该文档很少更改,因此我想做这样的事情...
1)应用启动后,获取文档并将其存储在本地。
2)设置一个侦听器,以便在文档更改时更新本地副本。
3)更新本地副本后,将此更改广播到可能正在使用该文档的任何小部件。
这是我希望Firestore默认工作的方式。
这是一个好主意吗?关于如何实施此建议?
这就是我最终要做的。实际上,这很简单。我将其实现为静态类,并且不确定这是否是最佳方法。但是我喜欢其他一切。
我创建了一个类,该类为文档设置了侦听器,还提供了更新文档的流。作为辅助工作,我的班级还将文档解析为Map并对游戏进行排序。
import 'package:cloud_firestore/cloud_firestore.dart';
import 'dart:async';
import 'package:pari/game.dart';
class Schedule {
static Map<String, Game> games = Map<String, Game>();
static StreamController<Map<String, Game>> _onUpdateController = StreamController.broadcast();
static Stream get onUpdate => _onUpdateController.stream;
static void setupListener() {
print('setupListener');
DocumentReference reference = Firestore.instance.collection('schedule').document('2018');
reference.snapshots().listen((documentSnapshot) {
print('listen begin');
List<Game> sortedList = List<Game>();
documentSnapshot.data.values.forEach((value) {
Game game = Game.fromMap(value);
sortedList.add(game);
});
sortedList.sort((a,b) => a.startTime.compareTo(b.startTime));
games.clear();
sortedList.forEach((game) {
games.addAll({game.key: game});
});
_onUpdateController.add(games);
print('listen end');
print('games: ${games.length}');
});
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句