Fetching data from sqflite and sending it to firebase - firebase

I made a local database using sqflite to save data locally and i need to send it to a firebase in need
so far the function i used to get the data is:
Future<List> getNameAndPrice() async{
Database db = await instance.database;
var result = await db.rawQuery('SELECT $columnName , $columnAmount FROM $table');
return result.toList();
}
the other function i use in the other page of flutter to get the data is:
Future sendtofirebase() async {
var orders = await dbHelper.getNameAndPrice();
print(orders);
}
so far the print is just to check the data i get and i get the data in this format:
I/flutter (21542): [{name: Regular burger, amount: 2}, {name: Cheese
burger, amount: 1}]
i just want to find a way to like fetch this data from the variable and then send it to the firebase database i've made firestore collectionreference and everything i just don't know how can i get the name alone and send it then send the amount of the item etc.. for each order (how to get each item individually and send it to the firebase db).
really looking forward for answers cause i've spent time looking and i am stuck there..
ps. i am still a beginner and i even don't know if i should use both sqflite and firebase
other than just saving everything in the firebase itself.. thank you for reading.

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
}

Firestore Collection (with Subcollection) to Sqflite Item in Flutter

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.

how to get firebase time in firebase

I needed in my app firebase (server) time millisecond. because my local time will be change by mobile date time setting,
i will be see this question by not so helpful,
Flutter Firestore Server side Timestamp
var timestamp=FieldValue.serverTimestamp();
print("timestamp"+timestamp.toString());
but they print below value
====>Instance of 'FieldValue'
you should use
timestamp() {
Firestore.instance.collection('timestamp').document('time').setData({
"timestamp": FieldValue.serverTimestamp(),
});
}
Before reading the timestamp you have to set it to the server since you are generating it from there. According to this
serverTimestamp() Returns a sentinel for use with set() or update() to include a server-generated timestamp in the written data.
so first set it
Firestore.instance.collection('timestamp').document('docId').setData({'time' : FieldValue.serverTimestamp()});
then get it using basic firestore query. Finally, check out this answer on the details of the why.
For more general way of getting timestamp
getTimestamp() async{
await Firestore.instance.collection('timestamp').document('docId').setData({'time' : FieldValue.serverTimestamp()});
DocumentSnapshot doc = await Firestore.instance.collection('timestamp').document('docId').get();
Timestamp timestamp = doc['time'];
var timestampInMilliSeconds = timestamp.millisecondsSinceEpoch;
return timestampInMilliSeconds;
/* here you can call setState to your own variable before returning and keep in mind this method is async so it will return a Future. */
}

Flutter: How to retrieve all the Firebase user data from its uid?

My database looks something like this:
Now as I start adding more and more data I will be getting variety of users. I want to extract data from one user based on their user ID. I tried using these codes but none of them worked. I am getting data in bulk of all the users but I just want one of them. Here's my attempt:
final data=await _collection.collection('UserDetails').getDocuments();
//print(user.uid);
DocumentReference ref = await _collection.collection('UserDetails').document(user.uid);
var lister=await ref.collection('Name');
print(lister);
This is the code for getting all their data:
for(var msgs in data.documents)
{
print(msgs.data);
}
I want a function or anything which could return data in this way:
function.giveUserID('uid').giveDataYouwanttoExtract('Attribute')
I can filter out using string conditions from all the data I am getting but as the database rises it will have to extract tons of data at once which will affect the performance and so I want to do this in this way. Please let me know if there's any way to just extract data of one user based on their uid or email or anything.
You can use queries. The code below returns all the users where name is equals to the Jack.
await _db.collection("UserDetails")
.where("Name", isEqualTo: "Jack")
.getDocuments()
.then((QuerySnapshot snapshot){
snapshot.documents.forEach((DocumentSnapshot documentSnapshot){
print(documentSnapshot.data);
});
});

Resources