jsonEncode fails with 'Converting object to an encodable object failed'
Unhandled Exception: Converting object to an encodable object failed: Instance of 'User'Short answer
jsonEncode only handles numbers, booleans, strings, null, lists and maps with string keys. For any other object it calls toJson(). The error means that call failed or returned something still not encodable. Add toJson to the class, return only encodable values from it, or pass toEncodable.
Fix it fast
1Find out which cause you have
Read the prefix of the message. 'failed' means calling toJson on the object threw, usually because the class has none. 'did not return an encodable object' means toJson ran but returned something that still cannot be encoded.
try { jsonEncode(value); } on JsonUnsupportedObjectError catch (e) { print(e.unsupportedObject.runtimeType); print(e.cause); }2Match what you see, then jump to its fix
- 1
Converting object to an encodable object failed: Instance of 'User'The class has no toJson methodFix - 2
Converting object did not return an encodable object: Instance of 'Address'toJson returns a map that still holds model objectsFix - 3
Converting object to an encodable object failed: Instance of 'DateTime' (or an enum, Duration, Uri)A value type that JSON does not support, such as DateTimeFix
- 1
What does the error look like?
Unhandled Exception: Converting object to an encodable object failed: Instance of 'User'Converting object did not return an encodable object: Instance of 'Address'JsonUnsupportedObjectError
Cause 1 of 3
The class has no toJson method
1Check
When toEncodable is not given, jsonEncode calls toJson() on every object it cannot encode directly. A class without that method makes the call fail, and the error stores the failure in cause.
print(e.cause); // the error thrown by the toJson call2Fix
Give the class a toJson method that returns a Map with string keys.
class User {
User(this.id, this.name);
final int id;
final String name;
Map<String, dynamic> toJson() => {'id': id, 'name': name};
}
final text = jsonEncode(User(1, 'Sana'));3Verify
The call returns a JSON string instead of throwing.
print(jsonEncode(User(1, 'Sana'))); // {"id":1,"name":"Sana"}Confirmed by api.flutter.dev
Cause 2 of 3
toJson returns a map that still holds model objects
1Check
The value returned by toJson must itself be directly encodable. A map that contains another model instance is not, unless that instance can be converted too. When toJson returns something that cannot be serialized, cause is null.
print(e.unsupportedObject.runtimeType); // the nested type, such as Address2Fix
Convert nested models inside the parent's toJson, and map list items the same way.
Map<String, dynamic> toJson() => {
'name': name,
'address': address.toJson(),
'tags': tags.map((t) => t.toJson()).toList(),
};3Verify
Encode the parent object again.
print(jsonEncode(user));Confirmed by api.flutter.dev
Cause 3 of 3
A value type that JSON does not support, such as DateTime
1Check
Directly encodable values are numbers, booleans, strings, null, lists and maps with string keys. DateTime and similar types are none of these.
print(e.unsupportedObject.runtimeType);2Fix
Convert the value yourself in toJson, or pass a toEncodable function that turns unsupported types into encodable ones.
final text = jsonEncode(
data,
toEncodable: (Object? o) {
if (o is DateTime) return o.toIso8601String();
throw UnsupportedError('Cannot encode ${o.runtimeType}');
},
);3Verify
Run the encode again and decode it to compare.
print(jsonDecode(text));Confirmed by api.flutter.dev
How do I stop it coming back?
- Give every model a toJson that returns only maps, lists, strings, numbers, booleans and null.
- Convert nested models and dates inside toJson, not at the call site.
- Add a round-trip test (encode, decode, compare) for each model.
Sources
How was this page made?
I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.
Which stack is behind this page?
Projects of mine built on the same technologies:
- TaxiDexMy own multi-tenant taxi dispatch SaaS: API, dispatcher portal, driver and passenger apps, and the servers underneath.
- Qist BazaarA buy-now-pay-later marketplace built from a blank repo, now past 100K downloads on Google Play.
- SessionBirdAn omnichannel engagement suite in Flutter: campaigns, chatbot, tickets, analytics and live calling.
Related fixes
Mobile apps
AudioCache has no play method after updating audioplayers
The method 'play' isn't defined for the type 'AudioCache'.
Since audioplayers 1.0, AudioCache only turns asset files into local files and caches them.
2 causes, each with a fixMobile apps
Flutter Bloc throws that emit was called after the event handler completed
emit was called after an event handler completed normally.
Each on<Event> handler gets its own Emitter, and it stops working the moment the handler's returned Future completes.
2 causes, each with a fixMobile apps
analysis_options.yaml: the URI it includes can't be found
include_file_not_found
The analyzer reports include_file_not_found when the file named after include: in analysis_options.yaml does not resolve.
2 causes, each with a fixMobile apps
Dart error: the body might complete normally and return null for a non-nullable type
body_might_complete_normally
Dart found a path through your function or callback that reaches the closing brace without a return.
3 causes, each with a fixMobile apps
Dart throws ConcurrentModificationError while looping over a list
ConcurrentModificationError
Dart throws this when a collection changes size while something iterates it.
2 causes, each with a fixMobile apps
Dart cannot turn a compact timestamp like 20201101153000 into a DateTime
FormatException: Invalid date format
DateTime.parse accepts a subset of ISO 8601, and a time part must be introduced by T or a space.
2 causes, each with a fix