Flutter Firebase - Search for documents which contain a string for - firebase

I have a question regarding a request to retrieve data from Google Cloud Firestore with specific parameters in my Flutter project.
I use the following code to check if a string in Firebase equals to a search query performed by a user:
var snapshot = await firestoreInstance.collection('categories/subcategory/items')
.where("parameter", isEqualTo: searchQuery).get()
This works if the user types exactly the name of the parameter stored in Firestore. But what I want is that it also works if only part of the searchQuery string is stored in the Firestore parameter.
I found a solution on https://medium.com/flutterdevs/implement-searching-with-firebase-firestore-flutter-de7ebd53c8c9 for this. In the article an array is created with all possibile searches for the parameter. But I think that is a bit complex and you have to generate a lot of new data in Firestore just to search for the article.
Is there a way to do this in an easier way so that you can use an operator as "contains" instead of "isEqualTo" in Flutter with Firebase for the request?

var snapshot = await firestoreInstance
.collection('categories/subcategory/items')
.where(
'parameter',
isGreaterThanOrEqualTo: searchQuery,
isLessThan: searchQuery + 'z'
)
.get();

Try this:
var snapshot = await firestoreInstance
.collection('categories/subcategory/items')
.where(
'parameter',
isGreaterThanOrEqualTo: searchQuery,
isLessThan: searchQuery.substring(0, searchQuery.length - 1) +
String.fromCharCode(searchQuery.codeUnitAt(searchQuery.length - 1) + 1),
)
.get();
I based the variable names on your example.

Related

Fetching multiple documents at the same time

I'm trying to fetch multiple documents but I'm unable to do it. I wanted to fetch multiple documents containing my search criteria.
Here's what I tried.
final FirebaseFirestore db = FirebaseFirestore.instance;
QuerySnapshot<Map<String, dynamic>> querySnapshot = await db
.collection('MyCollection')
.where('FldName', 'in', ['123', '345', '111']).get();
Error on the syntax which is pointing in the 'in':
Too many positional arguments: 1 expected, but 3 found.
Here's what my firebase looks like.
You need to use whereIn like this:
.where('FldName', whereIn: ['123', '345', '111']).get();
Not, in as a String.
The where query might be incorrect, try using this one that I got from the docs.
.where('FldName', arrayContainsAny: ['123', '345', '111'])

How can I update value of the field of the document by userID Field without doc ID in the Firebase collection in flutter?

I want to update value of the field's document. I wrote a query but it doesn't work.
**//this query is working, I hava a doc Id**
final CollectionReference _company = FirebaseFirestore.instance
.collection('Company')
..where(FieldPath.documentId, isEqualTo: _auth.currentUser!.uid);
**// But this query is not working, because I have not doc** ID, its doc ID auto gen. ID in firebase
final CollectionReference _companyAdvert =
FirebaseFirestore.instance.collection('CompanyAdvert')..where('userId', isEqualTo: _auth.currentUser!.uid) ;
all the code here
To update a document field in firestore, you need to write
await FirebaseFirestore.instance
.collection('CompanyAdvert')
.doc(id)
.update({ 'profileImage': *new profile image* });
You must understand that to update a firestore document, you must keep a reference of the document id in the document itself. You can think of this as the primary key for the document.
There are two ways to do this.
1. Get a reference to the newly created document, and then get the id from the reference.
Then update the document with this id
2. Generate a random id locally and use that as the document id.
You can do this with the [Uuid package][1] on pub.dev
The first step goes like this:
// first, create a document using the add method
DocumentReference docRef = await FirebaseFirestore.instance
.collection('CompanyAdvert')
.add(*data*);
// then extract the generated document id
String id = docRef.id;
// then save it back to the document using
await FirebaseFirestore.instance
.collection('CompanyAdvert')
.doc(id)
.update({'id': id});
The second step goes like this:
String id = const Uuid().v4();
await FirebaseFirestore.instance.collection('CompanyAdvert').doc(id).set(*data*);
// Make sure you add the id as one of the fields to the map data
Note that the first step incurs a write operation which will count against your total quota for firebase. I recommend you use the second approach
Visit the FlutterFire documentation to learn more

using two queries to get 'data1' OR 'data2' in flutter firebase

I want to get data from firebase only if the user is not saved in the document. Because I need a or-query, which is not possible in Firebase, I decided to use RxDart's CombinedStreams with two steams:
var streamOne = FirebaseFirestore.instance
.collection('jobs')
.where('jobState', isEqualTo: 1)
.where('userOne', isNotEqualTo: FirebaseAuth.instance.currentUser!.uid)
.snapshots();
var streamTwo = FirebaseFirestore.instance
.collection('jobs')
.where('jobState', isEqualTo: 1)
.where('userTwo', isNotEqualTo: FirebaseAuth.instance.currentUser!.uid)
.snapshots();
But my app shows the data even if the current user is in 'userOne' OR 'userTwo'. Is it possible to avoid this and get the data just if the currentUser is not 'userOne' OR 'userTwo'?
Your logic is flawed: if the UID is in userOne, the second query will still return that document, and vice versa. What you want is actually an AND: the documents where the UID is not in userOne and not in userTwo.
Unfortunately though that query also isn't possible on Firestore, as all not-equal conditions in a query must be on the same field.
There is no way to capture your logic in a single query, and you will have to filter the documents fo userOne and userTwo in your application code instead.

Flutter and Firebase - Get Specific Documents From Firebase

When you go into posts collection there are documents based on userId. And inside a document there is a new collection named userPosts. Inside userposts you can find postId and the details about the post.
I can get specific user post by using this code
postRef = Firestore.instance.collection('posts');
QuerySnapshot snapshot = await postRef
.document(userId)
.collection('userPosts')
.getDocuments();
But I want to get all the user posts without naming a specific user. How could I achieve this?
You can use a collection group query to query documents among all collections with same name.
QuerySnapshot snapshot = await Firestore.instance
.collectionGroup('userPosts')
.getDocuments();

Flutter firestore compound query

i'd like to know if there's a way to query firebase firestore collection in Flutter adding more than one field to the query. I tried some ways but i didn't realize how to do that. For example:
CollectionReference col = Firestore.instance
.collection("mycollection");
col.where('nome', isEqualTo: 'Tyg');
col.where('valor', isLessThan: '39');
Someone, please, have some way to do that? i am new in flutter and not getting the way.
Building Firestore queries follows a "builder pattern". Every time you call where it returns a new query object. So the code you have constructs two queries, that you don't assign to anything.
CollectionReference col = Firestore.instance
.collection("mycollection");
Query nameQuery = col.where('nome', isEqualTo: 'Tyg');
Query nameValorQuery = nameQuery.where('valor', isLessThan: '39');

Resources