Чтобы получить отдельный документ из Firestore с помощью Flutter и Dart, вы можете использовать пакет Firebase Firestore. Вот несколько методов с примерами кода, которые помогут вам в этом:
Метод 1: использование document()и get()
import 'package:cloud_firestore/cloud_firestore.dart';
Future<DocumentSnapshot> getDocument(String path) async {
DocumentReference documentRef = FirebaseFirestore.instance.doc(path);
DocumentSnapshot snapshot = await documentRef.get();
return snapshot;
}
Использование:
DocumentSnapshot docSnapshot = await getDocument('collection/documentId');
Метод 2: использование collection()и doc()с get()
import 'package:cloud_firestore/cloud_firestore.dart';
Future<DocumentSnapshot> getDocument(String collection, String documentId) async {
DocumentReference documentRef = FirebaseFirestore.instance.collection(collection).doc(documentId);
DocumentSnapshot snapshot = await documentRef.get();
return snapshot;
}
Использование:
DocumentSnapshot docSnapshot = await getDocument('collection', 'documentId');
Метод 3. Использование StreamBuilder для обновлений в реальном времени
import 'package:cloud_firestore/cloud_firestore.dart';
StreamBuilder<DocumentSnapshot> buildDocumentStreamBuilder(String path) {
DocumentReference documentRef = FirebaseFirestore.instance.doc(path);
return StreamBuilder<DocumentSnapshot>(
stream: documentRef.snapshots(),
builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}
if (!snapshot.hasData) {
return Text('Document does not exist');
}
DocumentSnapshot docSnapshot = snapshot.data!;
// Process and display the document data
return Text(docSnapshot.data().toString());
},
);
}
Использование:
StreamBuilder<DocumentSnapshot> streamBuilder = buildDocumentStreamBuilder('collection/documentId');
Метод 4: использование get()с then()
import 'package:cloud_firestore/cloud_firestore.dart';
Future<void> getDocument(String path) async {
DocumentReference documentRef = FirebaseFirestore.instance.doc(path);
documentRef.get().then((DocumentSnapshot snapshot) {
if (snapshot.exists) {
// Document exists
print(snapshot.data());
} else {
// Document does not exist
print('Document does not exist');
}
});
}
Использование:
await getDocument('collection/documentId');
Метод 5: использование QuerySnapshotс where()
import 'package:cloud_firestore/cloud_firestore.dart';
Future<void> getDocument(String collection, String documentId) async {
QuerySnapshot querySnapshot = await FirebaseFirestore.instance
.collection(collection)
.where(FieldPath.documentId, isEqualTo: documentId)
.get();
if (querySnapshot.size > 0) {
DocumentSnapshot docSnapshot = querySnapshot.docs[0];
print(docSnapshot.data());
} else {
print('Document does not exist');
}
}
Использование:
await getDocument('collection', 'documentId');