how to solve Unhandled Exception: Converting object to an encodable object failed?
385
get_storage
package uses json.encode
and json.decode
to save and load data from a file. And json.encode
/json.decode
documentation says that it can only serialize/deserialize classes if the toJson
and fromJson
functions are implemented respectively.
So, the code is going to look like this:
class Mesure {
late String equipement;
late String number;
late String courant = "";
Mesure.init(List<String> values) {
equipement = values[0];
number = values[1];
courant = values[2];
}
Mesure.fromJson(Map<String, dynamic> json)
: equipement = json['equipement'],
number = json['number'],
courant = json['courant'];
Map<String, dynamic> toJson() {
return {
'equipement': equipement,
'number': number,
'courant': courant,
};
}
}
class DataBase {
final int id;
final Mesure mesure;
final String status;
DataBase.init(this.id, this.mesure, this.status);
DataBase.fromJson(Map<String, dynamic> json)
: id = json['id'],
mesure = Mesure.fromJson(json['mesure']),
status = json['status'];
Map<String, dynamic> toJson() {
return {
'id': id,
'mesure': mesure.toJson(),
'status': status,
};
}
}
Author by
Abmb
Updated on January 05, 2023Comments
-
Abmb over 1 year
I created 2 classes the first one is :
class Mesure { late String equipement; late String number; late String courant = ""; Mesure.init(List<String> values) { equipement = values[0]; number = values[1]; courant = values[2]; } }
and DataBase class :
class DataBase { late int? id; late Mesure? mesure; late String? status; DataBase.init(int id, Mesure mesure, String status) { id = id; mesure = mesure; status = status; } }
Now i initialized DataBase with some values :
Mesure mesure = Mesure.init(values); DataBase test = DataBase.init(0, mesure, "status");
and i want to store it in storage getX :
final box = GetStorage(); box.write('data', test);
but it does not work and throw an exception :
E/flutter (19759): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Converting object to an encodable object failed: Instance of 'DataBase'
-
Abmb almost 2 yearsit shows the same errors
-
ingmbk almost 2 yearshello thanks for response , i have a similar problem to this stackoverflow.com/questions/72830170/… can u help me .. my probelm is how to do if i must add some data and i wanted to be jump it when i don't have them thanks in advance
-
lepsch almost 2 yearsI'm going to check it...