Custom function for calculating total cost by using "price" field from the "value" collection

Custom Code

.

What have you tried so far?

According to title, I used code pilot and code pilot give me below code

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';

int calculateTotalPrice() {
  /// MODIFY CODE ONLY BELOW THIS LINE

  // calculate total price by using "price" field from the "value" collection
// calculate total price by using "price" field from the "value" collection and use "Future<int>"
// give me the total price of all documents in the "value" collection, output in integer
  final snapshot = await FirebaseFirestore.instance.collection('value').get();

  int totalPrice = 0;
  for (final doc in snapshot.docs) {
    final price = doc.data()['price'] as int; // Ensure price is an int
    totalPrice += price;
  }

  return totalPrice;

  /// MODIFY CODE ONLY ABOVE THIS LINE
}

But it is giving me error that you can only use await with an async function. And the worst part is that when I use async function like this

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';

Future<int> calculateTotalPrice() async {
  /// MODIFY CODE ONLY BELOW THIS LINE

  // calculate total price by using "price" field from the "value" collection
// calculate total price by using "price" field from the "value" collection and use "Future<int>"
// give me the total price of all documents in the "value" collection, output in integer
  final snapshot = await FirebaseFirestore.instance.collection('value').get();

  int totalPrice = 0;
  for (final doc in snapshot.docs) {
    final price = doc.data()['price'] as int; // Ensure price is an int
    totalPrice += price;
  }

  return totalPrice;

  /// MODIFY CODE ONLY ABOVE THIS LINE
}

Error is no more means red lines are just gone but I am not able to save it as it is saying there is error in this code.

Did you check FlutterFlow's Documentation for this topic?
No
1 reply