Home > Software engineering >  Get data for class from JSON - Flutter
Get data for class from JSON - Flutter

Time:08-24

I have a class "DilemmData" whose variables are loaded with data like this:

  if (prefs.containsKey('dilemms')) {
    MyApp.dilemmList = DilemmData.decode(prefs.getString('dilemms')!);
  }

Here is the class:

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

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

  static Map<String, dynamic> toJson(DilemmData dilemm) => {
        '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) {
    print('BOBA: ${json['plus']}');
    return DilemmData(
      plus: json['plus'],
      minus: json['minus'],
      percent: json['percent'],
      title: json['title'],
      date: json['date'],
    );
  }

  static String encode(List<DilemmData> dilemm) => json.encode(
        dilemm
            .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']);
  }

  static List<DilemmItemData> decode(String item) =>
      (json.decode(item) as List<dynamic>)
          .map<DilemmItemData>((dil) => DilemmItemData.fromJson(dil))
          .toList();
}

But the plus and minus variables are always empty. Does anyone know how to fix this?

CodePudding user response:

The following code snippet would do the trick. Converting a DilemmItemData from JSON was missing.

factory DilemmData.fromJson(Map<String, dynamic> json) {
  return DilemmData(
    plus: (json['plus'] as List)
        .map((json) => DilemmItemData.fromJson(json))
        .toList(),
    minus: (json['minus'] as List)
        .map((json) => DilemmItemData.fromJson(json))
        .toList(),
    percent: json['percent'],
    title: json['title'],
    date: json['date'],
  );
}
  • Related