Firestore Collection (with Subcollection) to Sqflite Item in Flutter - sqlite

My application is using firestore database. I design categories and its subcategories of the content by using subcollection.
To make offline mode feature;
I want to save this firestore data to sqflite database.
I learned that I convert firebase data map to text for sqlite
But I counl't find a way to locate the subcollections.
var catagorySnapshots =
await _firestore.collection("categories").getDocuments();
List _list = [];
catagorySnapshots.documents.forEach((_snapshot) {
CategoryInformation categoryInformation = CategoryInformation();
CategoryItem curCategory =
CategoryItem.fromCollection(_snapshot.documentID, _snapshot.data);
categoryInformation.categoryList.add(curCategory);
print(curCategory.title);
//
// sub collections
//
});

I know its too late to answer, this might help someone else.
You have to try getting the information from snapshot.data['field'] like so and covert it to text as well.
Let me know of that works.

Related

Flutter Firebase firestore append data with unique ID

I'm working on the Flutter app where users can save multiple addresses. Previously I used a real-time database and it was easier for me to push data in any child with a unique Id but for some reason, I changed to Firestore and the same thing want to achieve with firestore. So, I generated UUID to create unique ID to append to user_address
This is how I want
and user_address looks like this
And this is how it's getting saved in firestore
So my question Is how I append data with unique id do I have to create a collection inside users field or the above is possible?
Below is my code I tried to set and update even user FieldValue.arrayUnion(userServiceAddress) but not getting the desired result
var uuid = Uuid();
var fireStoreUserRef =
await FirebaseFirestore.instance.collection('users').doc(id);
Map locationMap = {
'latitude': myPosition.latitude,
'longitude': myPosition.longitude,
};
var userServiceAddress = <String, dynamic>{
uuid.v4(): {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
}
};
await fireStoreUserRef.update({'user_address': userServiceAddress});
If I use set and update then whole data is replaced with new value it's not appending, so creating a collection is the only solution here and If I create a collection then is there any issue I'll face?
You won't have any issues per se by storing addresses in a separate collection with a one-to-many relationship, but depending on your usage, you may see much higher read/write requests with this approach. This can make exceeding your budget far more likely.
Fortunately, Firestore allows updating fields in nested objects via dot notation. Try this:
var userServiceAddress = {
'complete_address': completedAddressController.text,
'floor_option': floorController.text,
'how_to_reach': howtoreachController.text,
'location_type': locationTag,
'saved_date': DateTime.now().toString(),
'user_geo_location': locationMap,
'placeId': addressId
};
await fireStoreUserRef.update({'user_address.${uuid.v4()}': userServiceAddress});

How to get data from firebase sub collection?

Im trying to get data from firebase but im a bit struggling . I have this videos collection where I saving video ids and thenevery video has documetnfield and also a sub collection called user votes . In side that im saving the user votes from the ratingbarindicator
this is how to collection looks
So what I want is every document of the user votes sub colletion and then the each rating field .
but how can I do that ?What I want is calculating that together Hope anyone can help
To read the data from all (sub)collections with a given name, you can use a collection group query.
FirebaseFirestore.instance
.collectionGroup('uservotes')
.get()
...
Also see:
Is wildcard possible in Flutter Firestore query?
Fetch all the posts of all the users from Cloud Firestore
you can go through collection and document like this with firebase:
final querySnapshot = await FirebaseFiresotre.instance.collection('videos').doc([theVideoDocumentID])
.collection('uservotes').get();
final docs = querySnapshot.docs;
for(final doc in docs) {
final data = doc.data();
//handle each document here
}

Create documents, sub collections in Firestore via flutter on screen loads

I want to achieve is when flutter screen loads a document should create in firestore in following order.
Document > Sub Collection > Document > Data Fields
I manage to create documents and sub collections in above order, but the first Document appear in italic. That's because the child collection, documents creating before parent document created.
But I couldn't able to fix the issue. I've modified the code now it's not even creating the document. Before this It created in italic mode. Now it's not at all.
Here is the code.
getCurrentUser().then((user) {
DocumentReference todayReference = firestoreInstance.collection('attendance').document(todayDate);
firestoreInstance.collection('profiles').where('user_id', isEqualTo: user).snapshots().listen((onData) {
onData.documents.forEach((f) {
CollectionReference todaySubCollection = todayReference.collection(f.documentID);
DocumentReference attendanceReference = todaySubCollection.document(f["name"].toString().toLowerCase());
Map<String,dynamic> mapData = new Map<String,dynamic>();
mapData['attendance_status'] = true;
mapData['in'] = true;
mapData['out'] = true;
firestoreInstance.runTransaction((transaction) async {
await transaction.set(attendanceReference, mapData);
});
});
});
});
Here getCurrentUser() is returning the logged in user id.
Each profiles assigned to a user.
So, What I'm trying to do is, once user logged in a document should create under attendance collection named today's date.
Then looping through each profiles where user_id is matched with logged in user, the matching results will be store as sub collection under today's date with profiles name field.
Then under the name (document), a transaction needs to run to set details like attendance_status, in & out.
Following images will show how previously documents created.
I need to find a way to create documents, collection without in italic mode. Any help would be appreciated.
"Italicized" documents are virtual/non-existent as mentioned in the docs. If a document only has a sub-collection, it will be a virtual/non-existent document. A workaround for this is by writing fields in the document, like what you've mentioned in the comments.

How to add 2 collections in Firestore using React Native?

I want to add 2 collections in Firestore in React Native.
Like JOIN can be used to add 2 tables. Is there any alternative for JOIN in Firestore to add collections?
I want to add these 2 collections users and users_2
How can I do this? Please help
At the time of writing it is not possible to query documents across collections in Firestore (it is apparently a feature that is on the roadmap however, see this recent blog post https://cloud.google.com/blog/products/databases/announcing-cloud-firestore-general-availability-and-updates -see bullet point "More features coming soon"-).
So that means that you'll have to issue two queries (one for each table, to get all the collection docs) and join/combine their results in your front end.
Another approach would be to duplicate your data (which is quite common in NoSQL world) and create a third collection that contains copies of all the documents.
For this last approach you could use a Batched Write as follows (in Javascript):
// Get a new write batch
var batch = db.batch();
var docData = {email: 'test#gmail.com', fullname: 'John Doe'}
// Set the value of doc in users collection
var usersRef = db.collection('users').doc();
batch.set(usersRef, docData);
// Set the value of doc in the allUsers collection (i.e. the third collection)
var allUsersRef = db.collection('allUsers').doc();
batch.set(allUsersRef, docData);
// Commit the batch
return batch.commit().then(function () {
// ...
});

Retrive node data from firebase database

I have linked my app with a firebase database and i am wanting to retrieve the string of one node from it.
The node I am wanting to retrieve is shown below with the name of 'timeStamp'. Is there a way i can retrieve this text and then print it?
The answer is covered in the Firebase documentation guide
Reading Data
and here's an example:
let ref = FIRDatabase.database().reference()
.child("Users+infomation/ff..etc/timeStamp")
ref?.observeSingleEvent(of: .value, with: { snapshot in
let val = snapshot?.value
print(val!)
})
*this is Swift 3

Resources