serializable 0.8.0

  • README.md
  • CHANGELOG.md
  • Example
  • Installing
  • Versions
  • 86

serializable

Build Status

This is a library that generates a serializable class from classes annotated with @serializable or @Serializable().

Getting Started

  1. Create a new dart project.
  2. add serializable dependency to your pubspec.yaml.
...
dependencies:
  ...
  serializable: any
  ...
  1. create a file in bin folder called models.dart and put next code on it:
library example.person;

import 'package:serializable/serializable.dart';

part 'models.g.dart';

class SimpleType {
  String id;
  String name;

  SimpleType(this.id, this.name);
}

@serializable
class Person extends _$PersonSerializable {
  int id;
  String name;
  var someDynamic;
  Map someMap;
  Map<String, int> otherMap;

  Address address;

  List<Address> otherAddresses;

  static final Map<String, SimpleType> list = {
    'minutes': new SimpleType('58c42d14f17f33ec6e2020ad', 'minutes'),
    'hours': new SimpleType('58c42d26f17f33ec6e2020ae', 'hours'),
    'percent': new SimpleType('58c42d4bf17f33ec6e2020b3', 'percent')
  };
}

@serializable
class Address extends _$AddressSerializable {
  int id;
  String street;
  String zip;
  String city;
  String state;
}

@serializable
class ClassWithMethod extends _$ClassWithMethodSerializable {
  void sayHello(String name) {
    print('Hello $name!');
  }
}

  1. create a file in bin folder called main.dart and put next code on it:
import 'dart:convert';

import 'models.dart';

main() {
  var p1 = new Person()
    ..id = 1
    ..name = 'person 1';

  // you can get/set attributes using bracket notations

  print("p1['id']: ${p1['id']}"); // prints `p1['id']: 1`
  print("p1['name']: ${p1['name']}"); //prints `p1['name']: person 1`
  p1['id'] = 1; // will set `p1.id` to `1`
  p1['name'] = 'person 1'; // will set `p1.name` to `person 1`

  try {
    p1['no_existing'];
  } catch (e) {
    print(e); // prints `FieldNotFoundException: The key "no_existing" doesn't exist on class "Person"`
  }

  // you can also use it to convert the object to/from Map

  print('p1.ToMap(): ${p1.toMap()}'); // prints `{id: 1, name: person 1}`
  var p2 = new Person()
    ..fromMap({"id": 2, "name": "person 2", 'address': new Address()..fromMap({'id': 1})});
  print('p2: {id: ${p2.id}, name: ${p2.name}, address.id: ${p2.address
      .id}}'); // prints `p2: {id: 2, name: person 2, address.id: 1}`

  var p3 = new Person()
    ..fromMap({
      "id": 3,
      "name": "person 3",
      'address': new Address()..fromMap({'id': 3}),
      'otherAddresses': [{'id': 4, 'street': 'street 4'}].map((e) => new Address()..fromMap(e)).toList()
    });
  print('p3: {id: ${p3.id}, name: ${p3.name}, address.id: ${p3.address.id}, otherAddresses[0].street:'
      ' ${p3.otherAddresses[0].street}}'); // prints `p3: {id: 3, name: person 3, address.id: 3}`

  // you can use it to convert the objects to/from JSON using
  // `dart:convert` library directly

  print('p1: ${JSON.encode(p1)}'); // prints `p1: {"id":1,"name":"person 1"}`

  var p4Map = JSON.decode('{"id": 3, "name": "person 3"}');
  var p4 = new Person()
    ..fromMap(p4Map);

  print('p4: {id: ${p4.id}, name: ${p4.name}}'); // prints `p4: {id: 4, name: person 4}`

  new ClassWithMethod()['sayHello']('world'); // prints `Hello world!`
}

  1. create a file in tool folder called build.dart and put next code on it:
import 'package:build_runner/build_runner.dart';
import 'package:serializable/action.dart';


main() async {
  // In next line replace `example/*.dart` for the globs you want to use as input, for example `**/*.dart`
  // to take all the dart files of the project as input.
  await build([serializableAction(const ['example/*.dart'])],deleteFilesByDefault: true);
}

  1. run tool/build.dart. Then you will see that the file bin/models.g.dart has been generated and it will contains the next code:
// GENERATED CODE - DO NOT MODIFY BY HAND

part of example.person;

// **************************************************************************
// Generator: SerializableGenerator
// **************************************************************************

abstract class _$PersonSerializable extends SerializableMap {
  int get id;
  String get name;
  dynamic get someDynamic;
  Map<dynamic, dynamic> get someMap;
  Map<String, int> get otherMap;
  Address get address;
  List<Address> get otherAddresses;
  void set id(int v);
  void set name(String v);
  void set someDynamic(dynamic v);
  void set someMap(Map<dynamic, dynamic> v);
  void set otherMap(Map<String, int> v);
  void set address(Address v);
  void set otherAddresses(List<Address> v);

  operator [](Object __key) {
    switch (__key) {
      case 'id':
        return id;
      case 'name':
        return name;
      case 'someDynamic':
        return someDynamic;
      case 'someMap':
        return someMap;
      case 'otherMap':
        return otherMap;
      case 'address':
        return address;
      case 'otherAddresses':
        return otherAddresses;
    }
    throwFieldNotFoundException(__key, 'Person');
  }

  operator []=(Object __key, __value) {
    switch (__key) {
      case 'id':
        id = __value;
        return;
      case 'name':
        name = __value;
        return;
      case 'someDynamic':
        someDynamic = __value;
        return;
      case 'someMap':
        someMap = __value;
        return;
      case 'otherMap':
        otherMap = __value;
        return;
      case 'address':
        address = __value;
        return;
      case 'otherAddresses':
        otherAddresses = __value;
        return;
    }
    throwFieldNotFoundException(__key, 'Person');
  }

  Iterable<String> get keys => const [
        'id',
        'name',
        'someDynamic',
        'someMap',
        'otherMap',
        'address',
        'otherAddresses'
      ];
}

abstract class _$AddressSerializable extends SerializableMap {
  int get id;
  String get street;
  String get zip;
  String get city;
  String get state;
  void set id(int v);
  void set street(String v);
  void set zip(String v);
  void set city(String v);
  void set state(String v);

  operator [](Object __key) {
    switch (__key) {
      case 'id':
        return id;
      case 'street':
        return street;
      case 'zip':
        return zip;
      case 'city':
        return city;
      case 'state':
        return state;
    }
    throwFieldNotFoundException(__key, 'Address');
  }

  operator []=(Object __key, __value) {
    switch (__key) {
      case 'id':
        id = __value;
        return;
      case 'street':
        street = __value;
        return;
      case 'zip':
        zip = __value;
        return;
      case 'city':
        city = __value;
        return;
      case 'state':
        state = __value;
        return;
    }
    throwFieldNotFoundException(__key, 'Address');
  }

  Iterable<String> get keys => const ['id', 'street', 'zip', 'city', 'state'];
}

abstract class _$ClassWithMethodSerializable extends SerializableMap {
  void sayHello(String name);

  operator [](Object __key) {
    switch (__key) {
      case 'sayHello':
        return sayHello;
    }
    throwFieldNotFoundException(__key, 'ClassWithMethod');
  }

  operator []=(Object __key, __value) {
    switch (__key) {
    }
    throwFieldNotFoundException(__key, 'ClassWithMethod');
  }

  Iterable<String> get keys => const [];
}

  1. Finally you can run the file bin/main.dart. If everything is ok you will see next output in console:
p1['id']: 1
p1['name']: person 1
FieldNotFoundException: The key "no_existing" doesn't exist on class "Person"
p1.ToMap(): {id: 1, name: person 1}
p2: {id: 2, name: person 2}
p1: {"id":1,"name":"person 1"}
p3: {id: 3, name: person 3}

0.8.0

  • upgrade to built_mirrors@0.7.0

0.7.0

  • upgrade to built_mirrors@0.6.0
  • rename phase.dart to action.dart
  • rename serializablePhase to serializableAction

0.6.1

  • rename key to __key and value to __value in generator

0.6.0

  • upgrade built_mirrors to version ^0.5.0
  • upgrade build_runner to version ^0.4.0
  • upgrade build to version ^0.10.0

0.5.0

  • upgrade built_mirrors to version ^0.4.0
  • upgrade sourge_gen to version ^0.7.0

0.4.0

  • upgrade built_mirrors to version ^0.3.0
  • upgrade sourge_gen to version ^0.6.0

0.3.3

  • upgrade built_mirrors to version ^0.2.2

0.3.2

  • enhance tests
  • add .travis.yml file
  • skip operators during generation

0.3.1

  • make generator ignore static types

0.3.0

  • remove packageName parameter from phase
  • upgrade built_mirrors to version ^0.2.0
  • upgrade build_test to version ^0.5.0

0.2.1

  • correct types for using with strong-mode.

0.2.0

-  add ability to get methods using strings, for example:

var sayHello = person['sayHello']; // will return `person.sayHello`

0.1.2

  • upgrade dependencies

0.1.1

  • Serializable annotation now extends Reflectable
  • add const constructor to SerializableMap
  • add const constructor template to SerializableGenerator

0.1.0

  • change name from ISerializable to SerializableMap
  • add FieldNotFoundError
  • rename serializable_phase.dart to phase.dart
  • rename serializable_generator.dart to generator.dart

0.0.2

  • add toMap adn fromMap methods to ISerializable

0.0.1

  • Initial version

example/main.dart

import 'dart:convert';

import 'models.dart';

main() {
  var p1 = new Person()
    ..id = 1
    ..name = 'person 1';

  // you can get/set attributes using bracket notations

  print("p1['id']: ${p1['id']}"); // prints `p1['id']: 1`
  print("p1['name']: ${p1['name']}"); //prints `p1['name']: person 1`
  p1['id'] = 1; // will set `p1.id` to `1`
  p1['name'] = 'person 1'; // will set `p1.name` to `person 1`

  try {
    p1['no_existing'];
  } catch (e) {
    print(e); // prints `FieldNotFoundException: The key "no_existing" doesn't exist on class "Person"`
  }

  // you can also use it to convert the object to/from Map

  print('p1.ToMap(): ${p1.toMap()}'); // prints `{id: 1, name: person 1}`
  var p2 = new Person()
    ..fromMap({"id": 2, "name": "person 2", 'address': new Address()..fromMap({'id': 1})});
  print('p2: {id: ${p2.id}, name: ${p2.name}, address.id: ${p2.address
      .id}}'); // prints `p2: {id: 2, name: person 2, address.id: 1}`

  var p3 = new Person()
    ..fromMap({
      "id": 3,
      "name": "person 3",
      'address': new Address()..fromMap({'id': 3}),
      'otherAddresses': [{'id': 4, 'street': 'street 4'}].map((e) => new Address()..fromMap(e)).toList()
    });
  print('p3: {id: ${p3.id}, name: ${p3.name}, address.id: ${p3.address.id}, otherAddresses[0].street:'
      ' ${p3.otherAddresses[0].street}}'); // prints `p3: {id: 3, name: person 3, address.id: 3}`

  // you can use it to convert the objects to/from JSON using
  // `dart:convert` library directly

  print('p1: ${JSON.encode(p1)}'); // prints `p1: {"id":1,"name":"person 1"}`

  var p4Map = JSON.decode('{"id": 3, "name": "person 3"}');
  var p4 = new Person()
    ..fromMap(p4Map);

  print('p4: {id: ${p4.id}, name: ${p4.name}}'); // prints `p4: {id: 4, name: person 4}`

  new ClassWithMethod()['sayHello']('world'); // prints `Hello world!`
}

1. Depend on it

Add this to your package's pubspec.yaml file:


dependencies:
  serializable: "^0.8.0"

2. Install it

You can install packages from the command line:

with pub:


$ pub get

with Flutter:


$ flutter packages get

Alternatively, your editor might support pub get or packages get. Check the docs for your editor to learn more.

3. Import it

Now in your Dart code, you can use:


import 'package:serializable/serializable.dart';
        
Version Uploaded Documentation Archive
0.8.0 Dec 4, 2017 Go to the documentation of serializable 0.8.0 Download serializable 0.8.0 archive
0.7.1 Sep 29, 2017 Go to the documentation of serializable 0.7.1 Download serializable 0.7.1 archive
0.7.0 Sep 20, 2017 Go to the documentation of serializable 0.7.0 Download serializable 0.7.0 archive
0.6.1 Sep 7, 2017 Go to the documentation of serializable 0.6.1 Download serializable 0.6.1 archive
0.6.0 Aug 17, 2017 Go to the documentation of serializable 0.6.0 Download serializable 0.6.0 archive
0.5.0 Aug 11, 2017 Go to the documentation of serializable 0.5.0 Download serializable 0.5.0 archive
0.4.0 Jul 28, 2017 Go to the documentation of serializable 0.4.0 Download serializable 0.4.0 archive
0.3.3 May 26, 2017 Go to the documentation of serializable 0.3.3 Download serializable 0.3.3 archive
0.3.2 May 24, 2017 Go to the documentation of serializable 0.3.2 Download serializable 0.3.2 archive
0.3.1 May 11, 2017 Go to the documentation of serializable 0.3.1 Download serializable 0.3.1 archive

All 18 versions...

Analysis

This feature is new.
We welcome feedback.
More details: scoring.

We analyzed this package, and provided a score, details, and suggestions below.

  • completed on Jan 17, 2018
  • Dart: 2.0.0-dev.15.0
  • pana: 0.9.1

Scores

Popularity:
Describes how popular the package is relative to other packages. [more]
73 / 100
Health:
Code health derived from static analysis. [more]
98 / 100
Maintenance:
Reflects how tidy and up-to-date the package is. [more]
100 / 100
Overall score:
Weighted score of the above. [more]
86

Platforms

Detected platforms: Flutter, server, web

No platform restriction found in primary library package:serializable/serializable.dart.

Suggestions

  • Package is pre-v1 release.

    While there is nothing inherently wrong with versions of 0.*.*, it usually means that the author is still experimenting with the general direction API.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=1.8.0 <2.0.0
analyzer ^0.30.0 0.30.0+4 0.31.0-alpha.2
build ^0.11.1 0.11.2
build_runner ^0.6.0 0.6.1 0.7.5+1
built_mirrors ^0.7.0 0.7.1
source_gen ^0.7.0 0.7.3
Transitive dependencies
args 1.2.0
async 2.0.3
barback 0.15.2+14
bazel_worker 0.1.9
build_barback 0.4.0+2 0.5.0+1
build_compilers 0.1.0 0.2.0
build_config 0.1.1 0.2.1
built_collection 1.6.2 3.0.1
built_value 4.3.3 4.6.1
charcode 1.1.1
cli_util 0.1.2+1
code_builder 2.4.0 3.0.0
code_transformers 0.5.1+3
collection 1.14.5
convert 2.0.1
crypto 2.0.2+1
csslib 0.14.1
dart_style 1.0.9
fixnum 0.10.6
front_end 0.1.0-alpha.4.1 0.1.0-alpha.7
glob 1.1.5
html 0.13.2+2
http_parser 3.1.1
io 0.3.1
isolate 1.1.0
json_annotation 0.2.2
kernel 0.3.0-alpha.1.1 0.3.0-alpha.4
logging 0.11.3+1
matcher 0.12.1+4
meta 1.1.2
mime 0.9.5
package_config 1.0.3
path 1.5.1
plugin 0.2.0+2
pool 1.3.4
protobuf 0.7.0
quiver 0.26.2 0.27.0
scratch_space 0.0.1+2
shelf 0.7.2
source_maps 0.10.4
source_span 1.4.0
stack_trace 1.9.1
stream_channel 1.6.3
stream_transform 0.0.9
string_scanner 1.0.2
typed_data 1.1.5
utf 0.9.0+3
watcher 0.9.7+6
yaml 2.1.13
Dev dependencies
build_test ^0.9.1
test ^0.12.0