SUM of fields in an List

Resolved

Collection : requests

Fields :

timestamp - DateTime

status - String

notes - string

totalQuantity - Integer

siteNames - String

employeeName - String

totalPrice - integer

fullCartlist - List < Data (requestDataType) >

created a data type called “ requestDataType” and app state called "cart" ( fullCartlist takes these value )

Its fields are:

itemName - string

price - integer

quantity - integer

ItemUnit - String

indPrice - Integer

now i want the "totalPrice" filed to be = SUM of all "indPrice"

i have achieved this using and app state "cartSum" but in my case its causing issues as i am building an app where user will input the price of an item ( i have set an action to update the price when value changes which is causing issue )

so here if some one writes 100 in text filed it writes it to the "cartSum" but if the value is changed again it again ads to the cart ( cant figure out a way to rest the cartsum here ") it should delete the value of only that filed the value has been changed ( as it happens when we delete item from a cart)

... i have written a function for this but it outputs Sum of all the "indPrices" across documents ...cant able to figure out how to do this for a single document

int? totalIndPriceSum(List<RequestsRecord>? requests) {
  /// MODIFY CODE ONLY BELOW THIS LINE

  if (requests == null || requests.isEmpty) {
    return null; // Return null if the requests list is null or empty
  }

  int sum = 0;
  for (var record in requests) {
    for (var item in record.fullCartlist) {
      sum += item.indPrice ?? 0; // Add the indPrice of each item to the sum
    }
  }

  return sum;

  /// MODIFY CODE ONLY ABOVE THIS LINE
}

here is a view of one of the document to have better idea

1 reply