bean_collector_generator

install

Add to pubspec

the latest version is pub package


dependencies:
  bean_collector_annotation: ^0.0.3

dev_dependencies:
  flutter_test:
    sdk: flutter
  build_runner: ^2.0.5
  bean_collector_generator: $latest_version

visit example to get more infomation

Usage

    1. create a class in your lib directory

import 'package:bean_collector_annotation/bean_collector_annotation.dart';

@BeanCollectorBase()
mixin BaseBeanMixin<T> {
  T fromJson(Map<dynamic, dynamic> json);
}

    1. add @BeanCollector() to your beans

import 'package:bean_collector_annotation/bean_collector_annotation.dart';

@BeanCollector()
class UserBean implements BaseBeanMixin<userBean>{
  @override
  UserBean fromJson(Map<dynamic, dynamic> json) {}
}

visit example code to get more infomation

Generated code

  • $ flutter pub run build_runner build

The file name is base_bean.bean_collector.dart

Where filename is the file name of the BaseBeanMixin class

// GENERATED CODE - DO NOT MODIFY BY HAND

import 'package:example/src/user_bean.dart';


class BeanCollector {

 static M fromJsonAsT<M>(dynamic json) {
    if (json is List) {
      return _getListChildType<M>(json);
    } else {
      return _fromJsonSingle<M>(json);
    }
  }

  static M _fromJsonSingle<M>(dynamic json) {

    String type = M.toString();

    if(type == (UserBean).toString()){
      return UserBean().fromJson(json)  as M;
    }
    
    throw Exception("not found");
  }

  static M _getListChildType<M>(List<dynamic> data) {
      if(<UserBean>[] is M){
      return data.map<UserBean>((e) => UserBean().fromJson(e)).toList() as M;
    }
    
    throw Exception("not found");
  }
}

visit example code to get more infomation

apply


UserBean userBean = BeanCollector.fromJsonAsT<UserBean>({});

visit example code to get more infomation

Libraries

bean_collector_generator