Custom function to find the code with highest value in a list.

Resolved

Hi guys, good night,

I'm trying to find the way to create a function to get the code with the highest value in a list.

I got a table in supabase which has two columns, one is the code and the other is the value, but the code can be repeated in differents rows and the value could be different in each row.

So I need to sum all the values per code then get the code with the highest value.

I tried this function and it work in the test function mode, but when I set the custom function in the text widget, it just return the default value and not the right result.

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/schema/structs/index.dart';
import '/backend/supabase/supabase.dart';
import '/auth/supabase_auth/auth_util.dart';

String? findMostSellingProduct(
  List<String>? productNames,
  List<double>? amounts,
) {
  /// MODIFY CODE ONLY BELOW THIS LINE

  // find the most selling product from a map list item, there are two, productNames and the amounts
  if (productNames == null ||
      amounts == null ||
      productNames.isEmpty ||
      amounts.isEmpty) {
    return null;
  }

  // Create a map to store the total amount for each product
  final Map<String, double> productAmounts = {};

  // Loop through the product names and amounts and add up the total amount for each product
  for (int i = 0; i < productNames.length; i++) {
    final String productName = productNames[i];
    final double amount = amounts[i];
    if (productAmounts.containsKey(productName)) {
      productAmounts[productName] = productAmounts[productName]! + amount;
    } else {
      productAmounts[productName] = amount;
    }
  }

  // Find the product with the highest total amount
  String? mostSellingProduct;
  double highestAmount = 0;
  productAmounts.forEach((productName, amount) {
    if (amount > highestAmount) {
      mostSellingProduct = productName;
      highestAmount = amount;
    }
  });

  return mostSellingProduct;

  /// MODIFY CODE ONLY ABOVE THIS LINE
}

This is the function setting:

And this is how I set this to the text widget with the custom function:

Somebody can help me to understand what I'm doing wrong?

2
1 reply