Flutter-Dart Firebase Get a Summe from Docs - android

I wanna get a Summe from Firebase with Flutter-Dart, i can with Stream Builder all Datas receiving but i wanna get a Summe-Total from Orders. For Example how much money did i earn for this month ? or How much money i have to Pay to my Owner ? My Firebase Database look like this,
[Firebase Struktur][1]
[1]: https://i.stack.imgur.com/E5zsM.png
I wanna get the Grand Total for all "betrag", i tried this like it , but its coming a null, how can i all Documents as List with choosed Feld with For Loop Grand total Calculating and show in the Text ?
var rechnungider = 0;
firestoreInstance.collection("rechnungen").doc().get().then((value) {
for (int i = value.data()!.length; i > value.data()!.length; i++) {
print(value.data());
rechnungider += int.parse(value.data()!["betrag"]);
}
box.write("rechnunggider", rechnungider.toString());
print("Rechnunggider Yenilendi:${box.read("rechnunggider")}");
//print(value.data.toString());
});
}
I wanna show without Document name, i mean all betrag data from all Documents.Total Value, Summe.
Thanks

Please do not calculate the sum of collections on the frontend. I can't warn you enough!
I would recommend to create a cloud function that saves the sum on another place in your database. It is the recommended approach for getting the sum for a value from a collection.
Let me know if you need an example for the functions to write.

Related

How can I store the user number like this (1,2,3...)?

When a new user signs up, there should be a property named userNo. which should be increased by 1 in each document, so that it would be easy to pick random users from db using that userNo. Basically, like each document holds a User number similar to Uid but not like Afhghdfh4hk545, it should be like userNo.23 and so one. If a new user signs up its userNo. should be 24. Here is what I have tried.
Stream dummy =
await FirebaseFirestore.instance.collection('users').snapshots();
var doclength = await dummy.length;
var userNo = (dummy == null || dummy == 0) ? 1 : doclength;
FirebaseFirestore.instance
.collection('users')
.doc(currentUser.uid)
.update({'userNo': userNo});
Alright, you'll need a "meta document" that has a field called something like "next_user_number".
Upon creating a new user, you check the number on that field and use it as the "UserNo" for the newest user.
And after that, you increase the "next_user_number" in the "meta document" by 1. (here you want to use FieldValue increment - search for "firestore increment" for how to do it.)
But... to be absolutely sure this will work even in cases when two users are signing up at the same time or other error-prone cases, make sure you use a "batch write".
A batch write means that both operations are done together, so both incrementing the "next_user_number" and creating the new user with the right "UserNo" number are going to be accurate. (search for "firesotre batch write" to learn more).
Okay, I solved it after drinking mugs of coffee. To all of the future visitors you can get the exact length of documents in that particular collection and then use then keyword and extract the value and store it in int variable. Then you can use extractedValue.size as the userNo.

Avoiding same chat when using Firestore

I'm making now a chat app by using the Firestore database and im thinking how to avoid the same chat to be created twice.
For example, if person A sends message to person B, I had like the message to enter the same chat collection as if person B send the message to person A.
I have found the following suggestion here
It recommends to compare the users UID which I know and construct some chatID based on the combination of those string.
private String setOneToOneChat(String uid1, String uid2)
{
if(uid1 <uid2){
return uid1+uid2;
}
else{
return uid2+uid1;
}
}
comparing the length of both UID doesn't work since all (or at least all I have seen are from the same length).
However, first I didn't really understand how to use math operator such as < on a string, second im not sure if it really catches all cases.
If there are any suggestions to implement such thing I would like to hear.
Thank you
The ordering should be based on the actual content of the strings, not just on their length.
So in Java/Android:
if(uid1.compareTo(uid2) > 0){
return uid1+uid2;
}
else{
return uid2+uid1;
}

Maintaining dynamically computed values in firebase

I have a simple firebase database: /rides is a list of simple objects like this
{
car: "Toyota"
minutes: 15
}
and I need to display sum of minutes of all the rides. The obvious solution is to load all the rides and calculate the sum. But if I have several hundreds of rides this is very slow, up to several seconds.
So it seems I have to maintain a separate field /totalMinutesin the database for this. But thus I will have to manually update /totalMinutes every time I add/remove/change a ride. Anyway this is not a big deal of work.
But what if I need to calculate total minutes only for a subset of rides? For instance only for "Toyota" cars or "Ford" cars? Manual maintaining /totalMinutesFord, /totalMinutesToyota now doesn't seem so easy.
So what is the correct way to maintain such dynamic values in firebase?
Firebase has no way to get automatically calculate values based on the data in your database.
So your two options are:
calculate the value whenever you update the data
retrieve all the data and calculate the value on the client
You already (wisely) decided that retrieving all data is not a good idea. Your users will be grateful for that.
So that leaves calculating the derived values whenever you update the data of a ride. I'm not sure why doing that for multiple values would be more difficult than doing it for a single value. It may be more code, but it's pretty much the same code:
var ride = { car: "Toyota", minutes: 15 };
ref = new Firebase('https://yours.firebaseio.com/');
ref.child('rides').push(ride);
ref.child('totalMinutes').transaction(function(current_value) {
return (current_value || 0) + ride.minutes;
});
ref.child('totalMinutes'+ride.car).transaction(function(current_value) {
return (current_value || 0) + ride.minutes;
})

Possible to query against the count of an included key?

I have an application where I need to return the first user found that meets certain criteria, some of that criteria is having a certain number of objects stored.
For example, let's say I want to return the first store I can find that has at-least 3 employees with atleast two children. I know, what an odd-ball example. So I would have a query something like this:
PFUser.query()?
.whereKey("objectId", notEqualTo: PFUser.currentUser()?.objectId!)
.includeKey("stores.employees.children")
// .whereCountForkey("stores.employees", greaterThan: 2)
// .whereCountForKey("stores.employees.children", greaterThan: 1)
.getFirstObject();
Notice the commented out lines, I'm trying to find a way to do soemthing like this in a single query. I'm using parse, which I believe uses MongoDB on the back end, but I don't believe you can execute custom database queries..?
This is a mobile application for both iOS and Android, although the code shown is in SWIFT I have two variations of the project. Examples in either swift, obj-C, Java, or C# will be fine.
Also more than happy with Cloud-code solutions.
There is an example in the documentation
var Team = Parse.Object.extend("Team");
var teamQuery = new Parse.Query(Team);
teamQuery.greaterThan("winPct", 0.5);
var userQuery = new Parse.Query(Parse.User);
userQuery.matchesKeyInQuery("hometown", "city", teamQuery);
userQuery.find({
success: function(results) {
// results has the list of users with a hometown team with a winning record
}
});

How to retrieve the sum of a column using Parse/Parse Cloud?

I've created an Android application that helps my dad with his daily income/outcome management (for business).
I need an option menu item that when clicked, queries the particular Parse Class for the sum of a certain column (of String type, but data is in numbers only). I had done this using SQLite and it was a piece of cake, but this NoSQL system lacks such basic functions.
I understand we have to use Parse Cloud Code to accomplish this, but I'm not sure on the how-tos as there isn't much documentation on how to use Cloud Code.
Respective Code can be shared on request, as I'm not sure of what block to share. Please help, thank you very much :)
How about after receiving a list from ParseQuery just sum all the rows with for each loop? No need for ParseCloud to my taste.
Also, You could already make a column of Number type, not String, but let's go with this:
int sum; //or double or float, whatever needed
done(List<ParseObject> list, ParseException e){
for (ParseObject p : list){
sum += Integer.valueOf(p.getString("yourColumnName"));
}
}
Should work like that.

Categories

Resources