getExpenseByPercentageEachMonth function

Future<List<Map<String, dynamic>>> getExpenseByPercentageEachMonth()

Implementation

Future<List<Map<String, dynamic>>> getExpenseByPercentageEachMonth() async {
  try {
    List<Map<String, dynamic>> userRecords = [];

    // Total amount in the account
    int totalAmount = await getExpense();

    // Fetch records
    final results = await getRecords("expenses");
    List items = results.items;

    // Calculate percentage for each expense
    for (var element in items) {
      int amount = int.parse(element.data['amount'].toString());
      double percentage = (amount * 100) / totalAmount.toDouble();

      // Round percentage to two decimal places
      percentage = double.parse(percentage.toStringAsFixed(2));

      userRecords.add({
        "name": element.data['name'],
        "color": element.data['color'],
        "amount": await getBarHeight(amount),
      });
    }

    // Print and return the list
    print(userRecords);
    return userRecords;
  } catch (e) {
    // Handle any errors that occurred during the asynchronous operations
    print("Error in getExpenseByPercentage: $e");
    return []; // or throw an error
  }
}