Would someone be able to help me with a custom action? I am trying to get the sum of all the pledges tied to a specific committee name. The database name is "Pledge_Users", the field for committees is called "committee_name", and the pledge field is named "pledge". I have written the code below with the argument "committeesum" as an unnullable string. I know I am missing something because it is coming back as 0. Thank you for any help.
// Automatic FlutterFlow imports
import '/backend/backend.dart';
import '/flutter_flow/flutter_flow_theme.dart';
import '/flutter_flow/flutter_flow_util.dart';
import '/custom_code/actions/index.dart'; // Imports other custom actions
import '/flutter_flow/custom_functions.dart'; // Imports custom functions
import 'package:flutter/material.dart';
// Begin custom action code
// DO NOT REMOVE OR MODIFY THE CODE ABOVE!
import 'package:cloud_firestore/cloud_firestore.dart';
Future<int> getsumcommittee(String committeename) async {
final FirebaseFirestore firestore = FirebaseFirestore.instance;
final CollectionReference committeeRef = firestore.collection('Pledge_Users');
try {
final QuerySnapshot querySnapshot = await committeeRef
.where('committee_name', isEqualTo: committeename)
.get();
return querySnapshot.docs.fold<int>(0,
(int sum, QueryDocumentSnapshot doc) {
final pledgeValue = doc['pledge'];
if (pledgeValue is int) {
return sum + pledgeValue;
} else if (pledgeValue is String) {
int? parsedValue = int.tryParse(pledgeValue);
if (parsedValue != null) {
return sum + parsedValue;
} else {
return sum; // Parsing failed, don't add to the sum.
}
} else {
return sum; // Unknown data type or null, don't add to the sum.
}
});
} catch (e) {
print('Error fetching data: $e');
throw e; // You might want to handle the error differently depending on your application's requirements.
}
}