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<int>' 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
2
Answers
You need to add await key word front of Firebase method. Like blow code
Future calculateTotalItemQty(
String? itemId,
String? businessId,
) async{
@Mike Yates The problem is that your function is attempting to return a
Future<int>
instead of just anint
. To resolve this, make your functionasync
and utilize theawait
keyword for the Firestore query.I hope this helps.