Home > Software engineering >  Define a class of several in json Flutter
Define a class of several in json Flutter

Time:08-24

I have a HomeItem class, it has some kind of class in a child out of several. I can't identify them. Each class nested in a child has the enum Home type to define

class HomeItem {
  String name;
  dynamic child;

  HomeItem({
    this.name = '',
    required this.child,
  });

  HomeItem.fromJson(Map<String, dynamic> json)
      : name = json['name'] ?? '',
        // if you write it like this then everything works
        child = Task.fromJson(json['child']);

        // As I wrote down it doesn't work:
        // child = json['child'].values.map((e) {
          // switch (HomeType.values.elementAt(e['type'])) {
            // case HomeType.chat:
              // return Chat.fromJson(e);
            // case HomeType.storageFile:
              // return StorageFile.fromJson(e);
            // case HomeType.todo:
              // return Todo.fromJson(e);
            // case HomeType.audioNote:
              // return AudioNote.fromJson(e);
            // default:
        // }});

}

I was prompted this way for a list, but not for a single item:

childrens =
        (json['childrens'] as List<dynamic>).map<dynamic>((dynamic e) {
          switch(HomeType.values.elementAt(e['type'])) {
            case HomeType.chat:
              return Chat.fromJson(e as Map<String, dynamic>);
            case HomeType.storageFile:
              return StorageFile.fromJson(e as Map<String, dynamic>);
          }
        }).toList();

Here is a JSON example for Task

{name: gg, child: {type: 2, todos: [{title: hello, isCompleted: false}, {title: gg, isCompleted: false}]}},

CodePudding user response:

The following would do the trick:

class HomeItem {
  String name;
  dynamic child;

  HomeItem({
    this.name = '',
    required this.child,
  });

  HomeItem.fromJson(Map<String, dynamic> json)
      : name = json['name'] ?? '',
        child = _childFromJson(json['child']);

  static dynamic _childFromJson(Map<String, dynamic> json) {
    switch (HomeType.values.elementAt(json['type'])) {
      case HomeType.chat:
        return Chat.fromJson(json);
      case HomeType.storageFile:
        return StorageFile.fromJson(json);
      case HomeType.todo:
        return Todo.fromJson(json);
      case HomeType.audioNote:
        return AudioNote.fromJson(json);
      default:
    }
  }
}
  • Related