Это пример примера для чтения данных из базы данных firestore, я рекомендую его для вашего приложения.
Модель [post.dart]
class PostItem {
final String id;
final String name;
PostItem({
this.id,
this.name
}) : assert(id != null && id.isNotEmpty),
assert(name != null && name.isNotEmpty);
PostItem.fromMap(Map<String, dynamic> data)
: this(
id: data['id'],
name: data['name']
);
Map<String, dynamic> toMap() => {
'id': this.id,
'name': this.name
};
}
Служба для управления данными в / из пожарного хранилища [PostStorage.dart]
import 'dart:async';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:your_app/models/post.dart';
final CollectionReference postCollection = Firestore.instance.collection('Posts');
class PostStorage {
static PostItem fromDocument(DocumentSnapshot document) => _fromMap(document.data);
static PostItem _fromMap(Map<String, dynamic> data) => new PostItem.fromMap(data);
Map<String, dynamic> _toMap(PostItem item, [Map<String, dynamic> other]) {
final Map<String, dynamic> result = {};
if (other != null) {
result.addAll(other);
}
result.addAll(item.toMap());
return result;
}
/// Returns a stream of data snapshots
Stream<QuerySnapshot> list() {
Stream<QuerySnapshot> snapshots = postCollection.snapshots();
return snapshots;
}
Future create(Post post) async {
final TransactionHandler createTransaction = (Transaction tx) async {
final DocumentSnapshot newDoc = await tx.get(postCollection.document());
final PostItem newItem = new PostItem(
id: newDoc.documentID,
name: post.name
);
final Map<String, dynamic> data = _toMap(newItem, {
'created': new DateTime.now().toUtc(),
});
await tx.set(newDoc.reference, data);
return data;
};
return Firestore.instance.runTransaction(createTransaction)
.then(_fromMap)
.catchError((e) {
print('dart error: $e');
return null;
});
}
Future<bool> update(PostItem item) async {
final TransactionHandler updateTransaction = (Transaction tx) async {
final DocumentSnapshot doc = await tx.get(postCollection.document(item.id));
await tx.update(doc.reference, _toMap(item));
return {'result': true};
};
return Firestore.instance.runTransaction(updateTransaction).then((r) {
return r['result'] == true; // forcefully cast to boolean
}).catchError((e) {
print('dart error: $e');
return false;
});
}
Future delete(String id) async {
final TransactionHandler deleteTransaction = (Transaction tx) async {
final DocumentSnapshot doc = await tx.get(postCollection.document(id));
await tx.delete(doc.reference);
return {'result': true};
};
return Firestore.instance.runTransaction(deleteTransaction).then((r) => r['result']).catchError((e) {
print('dart error: $e}');
return false;
});
}
}
На вашей странице для получения данных это крошечный код:
StreamSubscription<QuerySnapshot> postSub;
List<PostItem> listPost = [];
PostStorage postStorage = new PostStorage();
@override
void initState() {
findPost();
super.initState();
}
@override
void dispose() {
postSub?.cancel();
super.dispose();
}
/// Get all types from DB Firestore
findPost() {
postSub?.cancel();
// Listen Firestore
typeSub = postStorage.list().listen((QuerySnapshot snapshot){
// Get Value
final List<PostItem> listPost = snapshot.documents.map(PostStorage.fromDocument).toList();
setState(() {
this.listPost = listPost;
});
});
}