Home > Mobile >  Flutter abstract class with factory methods
Flutter abstract class with factory methods

Time:11-13

I am new to working with dart/flutter! Tell me pls how to correctly implement an abstract class in which a factory method is needed I have a large number of models with the same methods (factory Model.fromJsom, listFromJson)! I want to make an interface for such models, but I don’t understand how to make a factory method and a static in abstract class

Examples

class Post extends Equatable {
  Post({
    required this.id,
    required this.title,
  });
  final int id;
  final String title;
  @override
  List<Object> get props => [
    id,
    title,
  ];
  factory Post.fromJson(dynamic json) {
    return Post(
      id: json['id'] as int,
      title: json['name'] as String,
    );
  }
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'title': title,
    };
  }
  static List<Post> listFromJson(List<dynamic> json) {
    return json.map((value) => Post.fromJson(value)).toList();
  }
  @override
  String toString() {
    return '''Post { id: $id, title: $title }''';
  }
}

CodePudding user response:

I find it's always a headache to work with JSON array directly. The solution I find is to wrap the List inside another class, in this case ListPost as follows:

class Post {
  final int id;
  final String title;

  Post({required this.id, required this.title});

  factory Post.fromJson(Map<String, dynamic> json) => Post(
        id: json['id'] as int,
        title: json['title'] as String,
      );

  Map<String, dynamic> toJson() => <String, dynamic>{
        'id': id,
        'title': title,
      };
}

class ListPost {
  final List<Post> list;

  ListPost({required this.list});

  factory ListPost.fromJson(Map<String, dynamic> json) => ListPost(
        list: (json['list'] as List<dynamic>)
            .map((e) => Post.fromJson(e as Map<String, dynamic>))
            .toList(),
      );
  Map<String, dynamic> toJson() => <String, dynamic>{
        'list': list,
      };

}

And the example JSON is like this:

{
  "list": [
    {"id": 1, "title": "TITLE_1"},
    {"id": 2, "title": "TITLE_2"}
  ]
}

I hope this is workable for you.

CodePudding user response:

You can simply use this website it will convert your json to a dart file and you can easily call the methods .fromJson and .toJson to convert from json to entity and vice versa quicktype website

JSON source

{
  "greeting": "Welcome to quicktype!",
  "instructions": [
    "Type or paste JSON here",
    "Or choose a sample above",
    "quicktype will generate code in your",
    "chosen language to parse the sample data"
  ]
}

Dart file

import 'dart:convert';

Welcome welcomeFromJson(String str) => Welcome.fromJson(json.decode(str));

String welcomeToJson(Welcome data) => json.encode(data.toJson());

class Welcome {
    Welcome({
        this.greeting,
        this.instructions,
    });

    String greeting;
    List<String> instructions;

    factory Welcome.fromJson(Map<String, dynamic> json) => Welcome(
        greeting: json["greeting"] == null ? null : json["greeting"],
        instructions: json["instructions"] == null ? null : List<String>.from(json["instructions"].map((x) => x)),
    );

    Map<String, dynamic> toJson() => {
        "greeting": greeting == null ? null : greeting,
        "instructions": instructions == null ? null : List<dynamic>.from(instructions.map((x) => x)),
    };
}

  • Related