Im trying to sum an integer field in my firestore document collection, although I keep gettings errors. It looks like because firestore store integers as "num".
A value of type 'Future' can't be returned from the function 'calculateTotalItemQty' because it has a return type of 'int'.
import 'dart:convert';
import 'dart:math' as math;
import 'package:flutter/material.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:intl/intl.dart';
import 'package:timeago/timeago.dart' as timeago;
import '/flutter_flow/lat_lng.dart';
import '/flutter_flow/place.dart';
import '/flutter_flow/uploaded_file.dart';
import '/flutter_flow/custom_functions.dart';
import '/backend/backend.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import '/backend/schema/structs/index.dart';
import '/auth/firebase_auth/auth_util.dart';
int calculateTotalItemQty(
String? itemId,
String? businessId,
) {
/// MODIFY CODE ONLY BELOW THIS LINE
// sum value of all itemQty in purchaseLine where itemId is itemId and businessId is businessId
return FirebaseFirestore.instance
.collection('purchases')
.where('itemId', isEqualTo: itemId)
.where('businessId', isEqualTo: businessId)
.get()
.then((querySnapshot) {
int totalQty = 0;
querySnapshot.docs.forEach((doc) {
int value = doc['itemQty'];
totalQty += value.toInt();
});
return totalQty;
}).catchError((error) {
print('Error getting total item qty: $error');
return null;
});
/// MODIFY CODE ONLY ABOVE THIS LINE
}
Tried to use .toInt() but still not working
As others mentioned, you can make your function
async
and return a Future.However, in FlutterFlow's custom code section, "Custom Actions" can return a Future and not "Custom Function". So you can move the code under a Custom Action snippet and it should work.
You can call that custom action in your Action Flow Editor where you can get that return
int
value and then do whatever you want with it.