Reputation: 1398
For explaining what I am facing problem while creating a jsonstring from object list,I have created this basic demo, actually I am trying to create a backup file for saving records but I am getting an error while jsonEncode.
getting following error
Converting object to an encodable object failed: Instance of 'TransactionModel'
class TransactionModel {
String id;
bool isexpense;
DateTime date;
double amount;
TransactionModel({
this.amount = 0.00,
required this.id,
this.isexpense = true,
required this.date,
});
Map<String, dynamic> toJson() {
return {
'id': id,
'isexpense': isexpense,
'date': date,
'amount': amount,
};
}
}
void main() {
List<TransactionModel> trans = [
TransactionModel(
date: DateTime.now(),
id: '1',),
];
String result = jsonEncode(trans);//error bcz of jsonEncode
print(result);
}
Upvotes: 0
Views: 80
Reputation: 17940
You can't encode an object
with custom property like DateTime
, you need first convert it to map
, then encode it, try this:
void main() {
List<TransactionModel> trans = [
TransactionModel(
date: DateTime.now(),
id: '1',),
];
var listOfMap = trans.map((e) => e.toJson()).toList();
String result = jsonEncode(listOfMap);
print(result);
}
Upvotes: 1