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});
}
CodePudding user response:
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});
}
CodePudding user response:
You can just add the credit
and substract the debit
from your previousBalance
.
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 -= element.debit ?? 0;
previousBalance = element.credit ?? 0;
print(
"id: ${element.id}, debit: ${element.debit}, credit: ${element.credit}, balance: $previousBalance");
});
}
This will print
id: 1, debit: 0, credit: 100, balance: 2100
id: 1, debit: 50, credit: 0, balance: 2050
id: 1, debit: 250, credit: 0, balance: 1800
id: 1, debit: 0, credit: 250, balance: 2050
id: 1, debit: 0, credit: 1300, balance: 3350
id: 1, debit: 1000, credit: 0, balance: 2350