Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to get running balance from dart list

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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});
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading