最后,在GitHub issue 中的diegoveloper 评论的帮助下,我找到了解决方案。
这条评论
await Firestore.instance
.collection("Collection")
.getDocuments(source: source)
如果我决定每次都检查源代码然后使用它,或者我可以在开始一个新的 Flutter 项目时使用它,这是一个很好的解决方案,但现在我已经有很多代码需要更好的解决方案。所以我决定分叉 cloud_firestore 包并对其进行编辑。
你可以在这里找到它:https://github.com/ShadyBoshra2012/flutterfire/tree/master/packages/cloud_firestore
我编辑的内容:
- firestore.dart
// The source of which the data will come from.
static Source _source = Source.serverAndCache;
static Source get source => _source;
Future<void> settings(
{bool persistenceEnabled,
String host,
bool sslEnabled,
bool timestampsInSnapshotsEnabled,
int cacheSizeBytes,
Source source}) async {
await channel.invokeMethod<void>('Firestore#settings', <String, dynamic>{
'app': app.name,
'persistenceEnabled': persistenceEnabled,
'host': host,
'sslEnabled': sslEnabled,
'timestampsInSnapshotsEnabled': timestampsInSnapshotsEnabled,
'cacheSizeBytes': cacheSizeBytes,
});
if (source != null) _source = source;
}
query.dart
source = Firestore.source;92号线
document_reference.dart
source = Firestore.source;83号线
如何使用它?
因此,您可以使用 Google 的连接包以这种方式使用我的分叉存储库:https://pub.dev/packages/connectivity。
在pubspec.yaml 文件中添加我的分叉存储库
cloud_firestore:
git:
url: https://github.com/ShadyBoshra2012/flutterfire.git
path: packages/cloud_firestore
然后在您的第一个屏幕或主屏幕中
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.none) {
await Firestore.instance.settings(source: Source.cache);
} else {
await Firestore.instance.settings(source: Source.serverAndCache);
}
如果您想在更改连接状态时刷新源:
StreamSubscription subscription;
void initState() {
super.initState();
// Check the internet connection after each change
// of the connection.
subscription = Connectivity()
.onConnectivityChanged
.listen((ConnectivityResult result) async {
// Check the internet connection and then choose the appropriate
// source for it.
var connectivityResult = await (Connectivity().checkConnectivity());
if (connectivityResult == ConnectivityResult.none) {
await Firestore.instance.settings(source: Source.cache);
} else {
await Firestore.instance.settings(source: Source.serverAndCache);
}
});
}
@override
void dispose() {
super.dispose();
subscription.cancel();
}
所以我希望它适用于每个人看到它,并等待Flutter Team编写更好的解决方案。感谢大家的参与。