Home > Software engineering >  Saving a class within a class - Flutter
Saving a class within a class - Flutter

Time:08-24

I have class "DilemmData" which I need to save:

class DilemmData {
     double percent = 0;
     final String title;
     final String date;
     List<DilemmItemData> plus = [];
     List<DilemmItemData> minus = [];

     DilemmData(
       plus,
       minus, {
       this.percent = 0,
       this.title = '',
       this.date = '',
     });

     static Map<String, dynamic> toJson(DilemmData dilemm) {
       return {
         'percent': dilemm.percent,
         'title': dilemm.title,
         'date': dilemm.date,
         'plus': dilemm.plus.map((e) => e.toJson()).toList(),
         'minus': dilemm.minus.map((e) => e.toJson()).toList(),
       };
     }

     factory DilemmData.fromJson(Map<String, dynamic> json) {
       return DilemmData(
         json['plus'],
         json['minus'],
         percent: json['percent'],
         title: json['title'],
         date: json['date'],
       );
     }

     static String encode(List<DilemmData> pressure) => json.encode(
           pressure
              .map<Map<String, dynamic>>((dil) => DilemmData.toJson(dil))
              .toList(),
     );

     static List<DilemmData> decode(String dilemm) =>
         ((json.decode(dilemm) ?? []) as List<dynamic>)
              .map<DilemmData>((dil) => DilemmData.fromJson(dil))
              .toList();
      }

    class DilemmItemData {
        final int importance;
        final String argument;

        DilemmItemData({this.importance = 0, this.argument = ''});

        Map<String, dynamic> toJson() {
          return {
             'importance': importance,
             'argument': argument,
          };
        }

       factory DilemmItemData.fromJson(Map<String, dynamic> json) {
            return DilemmItemData(
              importance: json['importance'], argument: json['argument']);
       }
   }

There is save function:

        DilemmData dilemm = DilemmData(
               percent: 0,
               title: controller.text,
               date: clockString);

        SharedPreferences sharedPreferences =
          await SharedPreferences.getInstance();

          String data = jsonEncode(dilemm);
          sharedPreferences.setString('dilemms', data);

But when i try to save i get this error: JsonUnsupportedObjectError (Converting object to an encodable object failed: Instance of 'DilemmData'). Does anyone know how to save?

StackOverflow says I have a lot of code, but I don't know what else to write, I'll write random letters for this: shdjfhjjsdfjhwehfwouiehuwefuwefuwheugweghuweghuiweghuwueghuweweugihwueighuwhguwhgu

Here is the function to get the data:

  Future loadDillems() async {
      SharedPreferences sharedPreferences = await 
          SharedPreferences.getInstance();

      if (sharedPreferences.containsKey('dilemms')) {
            Map<String, dynamic> data =
            jsonDecode(sharedPreferences.getString('dilemms')!);
            MyApp.dilemmList = DilemmData.fromJson(data) as List<DilemmData>;
      }
   }

CodePudding user response:

When converting the "top" class using its toJson() method, make sure that the subsequent classes' toJson() methods is also called. As such:

'plus': dilemm.plus.map((e) => e.toJson()).toList(),

And you of course have to implement toJson() and fromJson() in DilemmItemData as well.

Edit:

Okey, so a couple of alternatives. First of all, you had to create the new toJson() (and soon also fromJson()) methods. That is good.

As @Ivo wrote, if you pass the object to jsonEncode as you do now, then the methods cannot be static. But you could also pass DilemmData.toJson(dilemm) as:

String data = jsonEncode(DilemmData.toJson(dilemm));

But I'd recommend as @Ivo wrote to make it non-static, as you did with the new toJson method, and of course keep the toJson in DilemmItemData, and I suggest that you write the fromJson as well...

Second edit:

Your fromJson have to be a bit sharper. Something like this:

DilemmData(
  (json['plus'] as List<dynamic>)
          .map((e) => DilemmItemData.fromJson(e as Map<String, dynamic>))
          .toList(),

Edit 3:

You are saving one DilemmData, so you have to read it as one (1) DilemmData. Remove the as List<DilemmData>; It is not all of a sudden a List when it is one object that you save (String data = jsonEncode(dilemm);)

So do as follows:

final oneDilemmData = DilemmData.fromJson(data);

CodePudding user response:

I think you need to make your toJson() non static like this:

Map<String, dynamic> toJson() {
    return {
        'percent': percent,
        'title': title,
        'date': date,
        'plus': plus,
        'minus': minus,
    };
}

your encode could be like this then:

static String encode(List<DilemmData> pressure) => json.encode(
    pressure
        .map<Map<String, dynamic>>((dil) => dil.toJson())
        .toList(),
);
  • Related