Datacollection - This will help to generate the data collection in *.g.dart file from api response

Overview

datacollection

this will help to generate the data collection in *.g.dart file from api response

usage

Add the generator to your dev dependencies

pubspec.yaml

dependencies:
  datacollection: any
  json_annotation: any
  logger: any # log any value
  dio: any # for handle http client
  retrofit: any # for generation dio route

dev_dependencies:
  datacollection_generator: any
  http_mock_adapter: any
  retrofit_generator: any
  build_runner: '>2.3.0 <4.0.0' 
  json_serializable: '>4.4.0'

dart annotation

example

create a student model and named student.dart

import 'package:datacollection/datacollection.dart';
import 'package:json_annotation/json_annotation.dart';

part 'student.g.dart';

@JsonSerializable()
@paginations
@collections
@response
class Student {
  final String? name;
  final num? grade;
  final num? score;

  Student({
    this.name,
    this.grade,
    this.score,
  });

  factory Student.fromJson(Map<String, dynamic> json) =>
      _$StudentFromJson(json);

  Map<String, dynamic> toJson() => _$StudentToJson(this);

  factory Student.fromMap(Map<String, dynamic> map) => _$StudentFromJson(map);

  Map<String, dynamic> toMap() => _$StudentToJson(this);
}

create a post model and name post.dart

import 'package:collection/collection.dart';
import 'package:dio/dio.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:datacollection/datacollection.dart';
import 'package:retrofit/retrofit.dart';

part 'post.g.dart';

@RestApi(baseUrl: 'https://mylekha.app/api/v1/app/')
abstract class ClientPost {
  factory ClientPost(Dio dio, {String baseUrl}) = _ClientPost;

  @GET("/posts")
  Future<PaginationResponse<Post>> getPosts();

  @GET("/posts/{id}")
  Future<HttpResponse<Post>> getPost(@Path("id") int id);
}

@JsonSerializable()
@datacollections
class Post {
  @JsonKey(defaultValue: null)
  final int? id;

  @JsonKey(defaultValue: "")
  final String? slug;

  @JsonKey(defaultValue: "")
  final String? title;

  @JsonKey(defaultValue: "")
  final String? content; // post content

  @JsonKey(defaultValue: "post")
  final String? type; // post type

  @JsonKey(defaultValue: null)
  final String? link; // post link for video or audio

  @JsonKey(defaultValue: <String>[])
  final List<String>? images;

  @JsonKey(defaultValue: "en_US")
  final String? locale;

  Post({
    this.id,
    this.slug,
    this.title,
    this.content,
    this.type,
    this.link,
    this.images,
    this.locale,
  });

  factory Post.fromJson(Map<String, dynamic> json) => _$PostFromJson(json);

  Map<String, dynamic> toJson() => _$PostToJson(this);

  factory Post.fromMap(Map<String, dynamic> map) => _$PostFromJson(map);

  Map<String, dynamic> toMap() => _$PostToJson(this);

  Post copyWith({
    int? id,
    String? slug,
    String? title,
    String? content,
    String? type,
    String? link,
    List<String>? images,
    String? locale,
  }) {
    return Post(
      id: id ?? this.id,
      slug: slug ?? this.slug,
      title: title ?? this.title,
      content: content ?? this.content,
      type: type ?? this.type,
      link: link ?? this.link,
      images: images ?? this.images,
      locale: locale ?? this.locale,
    );
  }

  @override
  String toString() {
    return 'Post(id: $id, slug: $slug, title: $title, content: $content, type: $type, link: $link, images: $images, locale: $locale)';
  }

  @override
  bool operator ==(Object other) {
    if (identical(this, other)) return true;
    final listEquals = const DeepCollectionEquality().equals;

    return other is Post &&
        other.id == id &&
        other.slug == slug &&
        other.title == title &&
        other.content == content &&
        other.type == type &&
        other.link == link &&
        listEquals(other.images, images) &&
        other.locale == locale;
  }

  @override
  int get hashCode {
    return id.hashCode ^
        slug.hashCode ^
        title.hashCode ^
        content.hashCode ^
        type.hashCode ^
        link.hashCode ^
        images.hashCode ^
        locale.hashCode;
  }
}

then run the generator

# dart
pub run build_runner build

# flutter	
flutter pub run build_runner build

Use it

void main() {
    var data = <Map<String, dynamic>>[
      ...List.generate(10, (i) => {"name": "mr.$i", "age": i, "pass": i.isEven})
          .toList()
    ];

    var collection = PaginationResponse(data: data);
    expect(
      List<Map<String, dynamic>>,
      (collection.value.runtimeType),
      reason:
          "without T type, collection.value should be list of Map<String, dynamic>",
    );

    var studentCollection = PaginationResponse<Student>(data: data);
}

annotation

    @JsonSerializable()
    @datacollections
    class User{

    }

or

    @JsonSerializable()
    @DataCollectionAnnotation(
        paginations: true,
        collections:true,
        response: true,
    )
    class User{

    }
You might also like...

Flutter file based routing - File based routing and nested layouts for Flutter

Flutter File Based Routing I was inspired by the routing in remix.run with neste

Sep 29, 2022

This project is a rebuild of the existing movie colony https://github.com/debbsefe/Movie-Colony. Here's also a link to the figma file https://www.figma.com/file/XpLFNEsROiN1z6lwnNHMrU/Movie-app?node-id=2956%3A10161

Tvfiy Generated by the Very Good CLI 🤖 A Very Good Project created by Very Good CLI. Getting Started 🚀 This project contains 3 flavors: development

Nov 12, 2022

Data Migrator - provide a universal translator for data by being portable, diverse, and efficient in migrating and converting data across discrete schemas

Data Migrator - provide a universal translator for data by being portable, diverse, and efficient in migrating and converting data across discrete schemas

Data Migrator - provide a universal translator for data by being portable, diverse, and efficient in migrating and converting data across discrete schemas

Jan 2, 2023

Flutter-Apps-Collection: a collection of apps made in flutter for learning purpose

 Flutter-Apps-Collection: a collection of apps made in flutter for learning purpose

Flutter-Apps-Collection This is a repository of a collection of apps made in flutter for learning purpose Some Screenshots . . . Apps build in Flutter

May 27, 2022

My collection of bricks created by me to help you build Flutter projects faster I think.

My collection of bricks created by me to help you build Flutter projects faster I think.

My collection of bricks created by me to help you build Flutter projects faster I think. 🧱 Bricks Brick Description Version presentation_layer A bric

Nov 15, 2022

My collection of bricks to help you build projects faster or nothing else will 😆

My collection of bricks to help you build projects faster or nothing else will 😆

My collection of bricks to help you build projects faster or nothing else will 😆 Bricks 🧱 Brick Description Version annoying_analysis_options A bric

Aug 20, 2022

ToDo App made with flutter which stores your todos based on their categories. The data is stored in external application storage in your device in JSON file.

ToDo App made with flutter which stores your todos based on their categories. The data is stored in external application storage in your device in JSON file.

⭐ My ToDo ⭐ Built with ❤︎ by Akash Debnath This is my second project on Flutter. This app hepls you to keep record of your ToDos. You can create your

Dec 25, 2022

A package help you to make api call and handle error faster, also you can check for internet before call api.

http_solver ##not for production use, only for learning purpose. A package help you to make api call and handle error faster, also you can check for i

Jun 18, 2020

Form builder fix - A package helps in creation of data collection forms in Flutter by removing the boilerplate needed to build a form

Flutter FormBuilder - flutter_form_builder This package helps in creation of dat

Jan 29, 2022
Owner
ke chankrisna
I have finished bachelor of Banking since 2014. Then start learning from short course and practice in coding until now.
ke chankrisna
Flutter Online dataCollection App for AI

eyu_data_collection A new Flutter project. Getting Started This project is a sta

Eyosiyas Tibebu 3 Jun 14, 2022
D info - Flutter package for response info message

D'Info Flutter package for response info message. It's like bootstrap view but s

Indra Trisna Raharja 4 Oct 26, 2022
Given a JSON string, this library will generate all the necessary Dart classes to parse and generate JSON.

JSON to Dart Given a JSON string, this library will generate all the necessary Dart classes to parse and generate JSON. This library is designed to ge

Javier Lecuona 1.2k Dec 25, 2022
State Persistence - Persist state across app launches. By default this library store state as a local JSON file called `data.json` in the applications data directory. Maintainer: @slightfoot

State Persistence Persist state across app launches. By default this library store state as a local JSON file called data.json in the applications dat

Flutter Community 70 Sep 28, 2022
Tool made in Dart that allows you to dynamically generate JSON files from data models written in Dart.

Dart JSON Generator Versión v1.1.1 Dart JSON Generator es una herramienta que permite generar archivos JSON a partir de mapas como modelos de datos en

Joinner Medina 7 Nov 23, 2022
Flutter video compress - Generate a new file by compressed video, and provide metadata. Get video thumbnail from a video path, supports JPEG/GIF. To reduce app size not using FFmpeg in IOS.

flutter_video_compress Generate a new path by compressed video, Choose to keep the source video or delete it by a parameter. Get video thumbnail from

天海るり 179 Dec 8, 2022
🔒 Desktop GUI to generate file checksum (SHA and MD5).

Note currently this app is only available for Windows and Linux. File Checksum File checksum is an old technique to verify the integrity of a file. An

Alex Rintt 6 Jan 3, 2023
This is a command-line app written on dart language for flutter applications that will help you to generate some boilerplate code

dart-generator Manual installation: 1- generate a platform executable from code dart compile exe main.dart -o generator this will generate a new gene

One Studio 11 Oct 26, 2022
Beautiful Weather App using API with support for dark mode. Created by Jakub Sobański ( API ) and Martin Gogołowicz (UI, API help)

Flutter Weather App using API with darkmode support Flutter 2.8.1 Null Safety Beautiful Weather App using https://github.com/MonsieurZbanowanYY/Weathe

Jakub Sobański 5 Nov 29, 2022
A simple flutter app that downloads a file from the internet, shows a custom-made download progress dialog and saves the file to device's internal storage

http_downloader A simple flutter app that downloads a file from the internet using the http plugin. It has a custom-designed progress dialog which dis

Akora Ing. Debrah Kwesi Buabeng 4 Apr 6, 2021