Home > Mobile >  how to solve Unhandled Exception: Converting object to an encodable object failed?
how to solve Unhandled Exception: Converting object to an encodable object failed?

Time:06-18

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'

CodePudding user response:

please try this

class DataBase {
  int? id;
  Mesure? mesure;
  String? status;
  DataBase(this.id, this.mesure, this.status);
}

Then use

Mesure mesure = Mesure.init(values);
DataBase test = DataBase(id:0, mesure : mesure, status:"status");

CodePudding user response:

get_storage package uses json.encode and json.decode in the sources to save and load data from a file. And json.encode/json.decode documentation says that it can only serialize/deselialize 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,
    };
  }
}
  • Related