Merge two streams coming from firebase firestore Flutter - firebase

I want two streams to be combined as one result and then return it from my function. I have two streams coming from firebase. So I have to merge data1 into data2, something like concatenation of both the streams and then return. What i have acheived so for is:
Future<Stream<QuerySnapshot>> getMsgs(userId, toId) async {
var data1 = await _fireStore
.collection(_collection)
.where('messageFrom', isEqualTo: userId).where('messageTo', isEqualTo: toId)
.orderBy('createdOn', descending: true)
.snapshots();
var data2 = await _fireStore
.collection(_collection)
.where('messageFrom', isEqualTo: toId).where('messageTo', isEqualTo: userId)
.orderBy('createdOn', descending: true)
.snapshots();
// I have tried this, but this will be the list
return [data1, data2];
// I have tried this, but didn't worked
return StreamZip([data1, data2]);
}
Any help would be appreciated.

Related

Flutter : How to get Stream Query with OR condition in [Firebase]

I want to implement OR condition in flutter using the multiple where(); method but this returns AND condition.
Following is my code for query
Future<Stream<QuerySnapshot>> getOrders() async {
return FirebaseFirestore.instance
.collection("Orders")
.orderBy("timestamp")
.where("isCredentialUploaded", isEqualTo: true),
.where("isTransactionDone", isEqualTo: true)
.snapshots();
}
But this makes the AND Condition, like this
if(isCredentialUploaded && isTransactionDone)
Is there any way I can get the OR condition in Firebase Firestore?
Result i want:
if(isCredentialUploaded || isTransactionDone)
In the official documentation of Firebase & Flutter we notice that after using the query we must use get() instead of snapshot().
Try this code:
Future<Stream<QuerySnapshot>> getOrders() async {
return FirebaseFirestore.instance
.collection("Orders")
.orderBy("timestamp")
.where("isCredentialUploaded", isEqualTo: true),
.where("isTransactionDone", isEqualTo: true)
.get();
}

flutter Stream from Cloud Firestore : how to copy data from snapshot to class and print

I have to stream the data from Cloud Firestore collection. How should I read the data from snapshot, and then print movieCode and movieName using print() function.
Future<Stream<QuerySnapshot<Object?>>> streamMovie() async
{
Stream<QuerySnapshot> snapshots =
FirebaseFirestore.instance.collection('movie')
.snapshots();
return snapshots;
}
You could try to use this way to get the data in printing.
void getMessagesTest() async{
QuerySnapshot querySnapshot = await _firestore.collection('school').orderBy('age', descending: true).where('age', isGreaterThan: 17).get();
final allData = querySnapshot.docs.map((doc) => doc.data() as Map<String, dynamic>).toList();
print(allData);
}

How to fetch data from firestore using .where(GreaterThan, and LessThan) condition. - Flutter

I'm trying to fetch data from firestore using the .where() condition.
Query adsRef = FirebaseFirestore.instance
.collection('All ads')
.where('adPrice',
isGreaterThanOrEqualTo: '2000')
.where('adPrice',
isLessThanOrEqualTo: '115000')
.limit(adsPerPage);
QuerySnapshot querySnapshot = await adsRef.get();
When using only one condition (eg: .where('adPrice',isGreaterThanOrEqualTo: '2000') ) works but dosen't fetch all documents[Just fetching random documents].
And when using both condtions it retruns null even though the DB has matching data.
Is there any other way to fetch data from firestore within two numbers? (in between 2000 to 115000)
Two inequality conditions are not valid in one firestore query. wrap you block of code in try catch and you will see the error.
Alternatively you can query both of your conditions separately and then merge the results like this:
void getAds() async {
List<Future<QuerySnapshot>> futures = [];
var firstQuery = FirebaseFirestore.instance
.collection('All ads')
.where('adPrice', isGreaterThanOrEqualTo: '2000')
.getDocuments();
var secondQuery = FirebaseFirestore.instance
.collection('All ads')
.where('adPrice', isLessThanOrEqualTo: '115000')
.getDocuments();
futures.add(firstQuery);
futures.add(secondQuery);
List<QuerySnapshot> results = await Future.wait(futures);
results.forEach((res) {
res.documents.forEach((docResults) {
print(docResults.data);
});
});
}
Please do try this and let me know if it works for you. Thanks

Merge two streams from Firestore together in Dart/Flutter

I have a chat feature that gets Firestore documents for both the current user and the person he/she is chatting with. I'm trying to merge these streams together, but when I use mergeWith or Rx.merge, it only returns the results of one stream.
Here is the function that gets the data:
fetchData(String userUid, String chatterUid) async {
var myChats = _messages
.document(userUid)
.collection('userMessages')
.document(chatterUid)
.collection('chats')
.orderBy('time', descending: true)
.snapshots();
var otherChats = _messages
.document(chatterUid)
.collection('userMessages')
.document(userUid)
.collection('chats')
.orderBy('time', descending: true)
.snapshots();
Rx.merge([otherChats, myChats]).listen((event) {
if (event.documents.isNotEmpty) {
_controller.add(event.documents.map((e) {
return Chat.fromData(e.data);
}).toList());
} else {
_controller.add(<Chat>[]);
}
});
Is there anyway to combine the results so that all the results are filtered into one stream that I can return?

How to make a one-time simple query with Firebase Firestore?

In Dart/Flutter and learning Firebase Firestore... I'm using the following method to test before creating UI:
_testFireStore() async {
var result = Firestore.instance
.collection('users')
.where('uid', isEqualTo: 'IvBEiD990Vh0D9t24l2GCCdsrAf1')
.snapshots();
await for (var snapshot in result) {
for (var user in snapshot.documents) {
print('main.DEBUG: ' + user.data.toString());
}
}
}
It works as expected -- the print statement is executed initially, but also subsequently in real-time every time any field is updated in the document in the Firestore database.
How can this code be changed such that the snapshot is only retrieved once -- not "subscribed/listened" to... and thus we don't waste bandwidth on unwanted/unneeded data and the print statement is only executed once?
Firestore.instance.collection(...).where(...) returns a Query object. It has a method called getDocuments() that executes the query and gives you a Future with a single set of results.
var query = Firestore.instance
.collection('users')
.where('uid', isEqualTo: 'IvBEiD990Vh0D9t24l2GCCdsrAf1');
query.getDocuments().then((QuerySnapshot snapshot) {
// handle the results here
})
Or use await to get the QuerySnapshot, since getDocumets() returns a Future.
Use getDocuments(), to retrieve all the documents once:
_testFireStore() async {
var result = await Firestore.instance
.collection('users')
.where('uid', isEqualTo: 'IvBEiD990Vh0D9t24l2GCCdsrAf1')
.getDocuments();
print(result.documents.toString());
}

Resources