how to get running balance from dart list

Issue

I have a table having columns id,debit,credit. I am fetching data from database and generating a list with the help of model. I want to calculate running balance from dart list which should be like this

Debit Credit Balance
0 200 200
100 0 100
100 0 0
void main() {
      List<LedgerModel> ledgerList;
      int? previousBalance = 2000;
      ledgerList = <LedgerModel>[
        LedgerModel(id: 1,debit: 0, credit: 100),
        LedgerModel(id: 1,debit: 50, credit: 0),
        LedgerModel(id: 1,debit: 250, credit: 0),
        LedgerModel(id: 1,debit: 0, credit: 250),
        LedgerModel(id: 1,debit: 0, credit: 1300),
        LedgerModel(id: 1,debit: 1000, credit: 0),
      ];
      
      ledgerList.forEach((element) {
        print("${element.id}   ${element.debit}   ${element.credit} ${(previousBalance+element.credit)-element.ebit}");
      });
      
    }
    
    class LedgerModel {
      int? id;
      int? debit;
      int? credit;
      
      LedgerModel({this.id,this.debit, this.credit});
    }

Solution

You need to store the value in previousBalance variable so that you can achieve the result like you expected

void main() {
  List<LedgerModel> ledgerList;
  int previousBalance = 2000;
  ledgerList = <LedgerModel>[
    LedgerModel(id: 1, debit: 0, credit: 100),
    LedgerModel(id: 1, debit: 50, credit: 0),
    LedgerModel(id: 1, debit: 250, credit: 0),
    LedgerModel(id: 1, debit: 0, credit: 250),
    LedgerModel(id: 1, debit: 0, credit: 1300),
    LedgerModel(id: 1, debit: 1000, credit: 0),
  ];

  ledgerList.forEach((element) {
    previousBalance =
        previousBalance + element.credit - element.debit;
    print(
        "${element.id}   ${element.debit}   ${element.credit} $previousBalance");
  });
}

class LedgerModel {
  int id;
  int debit;
  int credit;

  LedgerModel({required this.id, required this.debit, required this.credit});
}

Answered By – MSARKrish

Answer Checked By – Willingham (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.