Irfan Ganatra
Irfan Ganatra

Reputation: 1398

jsonEncode generating error while converting object to jsonstring in flutter

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

Answers (1)

eamirho3ein
eamirho3ein

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

Related Questions