I have a class as below:
class Account {
Account({
required this.balance,
});
late final double balance;
Account.fromJson(Map<String, dynamic> json){
balance= json['balance'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['balance'] = balance;
return _data;
}
}
I have an array of this Account class. To calculate total of the balances of accounts I did:
double total = accounts.fold(0, (sum, item) => sum + item.balance);
Running this code I get this error:
Uncaught TypeError: item.get$balance is not a function
UPDATE:
This is a sample code to test on DartPad:
import 'dart:convert';
void main() {
String jsonStr = '[{"balance":20.5},{"balance":20.5}]';
// Not working
// List<Account> accounts = List.from(json.decode(jsonStr));
// double total = accounts.fold(0, (sum, item) => sum + item.balance);
// print(total);
// Works fine
// Account account = Account(balance: 20.5);
// List<Account> accounts2 = [account, account];
// double total = accounts2.fold(0, (sum, item) => sum + item.balance);
// print(total);
// Works fine
List<Account> accounts3 = List<Account>.from(json.decode(jsonStr)
.map((model) => Account.fromJson(model)));
double total = accounts3.fold(0, (sum, item) => sum + item.balance);
print(total);
}
class Account {
Account({
required this.balance,
});
late final double balance;
Account.fromJson(Map<String, dynamic> json){
balance= json['balance'];
}
Map<String, dynamic> toJson() {
final _data = <String, dynamic>{};
_data['balance'] = balance;
return _data;
}
}
Now my question is what is the differences first and last approaches?