0

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);
}

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

9 Comments

But I have already tried this
import 'dart:convert'; main() { User user = User('bezkoder', 21); String jsonUser = jsonEncode(user); print(jsonUser); }
I updated my answer, The example that you provide only works when you define TransactionModel with string or int or variable like that, not works with dateTime, if you want to use this kind of variable you need to convert it the way I answerd. @IrfanGanatra
The approach in that page won't works on dynamic classes as property, its only works when you use static type like string, int,... . @IrfanGanatra
Yes..I got your point and checked with editing date:date.toString() in my code and it worked....So converting to map is compulsory while using such datetime..
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.