serializable 0.11.1

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

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 dependencies and build_runner to your dev_dependencies in the file pubspec.yaml .

...
dependencies:
  ...
  serializable: any   # change by the latest dependency
  ...
dev_dependencies:
  ...
  build_runner: any   # change by the latest dependency
  ...

3. 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!');
  }
}

4. 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: ${jsonEncode(p1)}'); // prints `p1: {"id":1,"name":"person 1"}`

  var p4Map = jsonDecode('{"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!`
}

5. run pub run build_runner build. 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;

// **************************************************************************
// 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 [];
}

6. 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.11.1

  • upgrade analyzer to version ^0.33.0
  • upgrade build_runner to version ^1.0.0
  • upgrade build to version ^1.0.1
  • upgrade built_mirrors_core to version ^0.10.1
  • upgrade serializable_core to version ^0.11.1

0.11.0

  • add from methods
  • upgrade built_mirrors to ^0.10.0
  • use SerializedName from built_mirrors

0.10.0

  • upgrade source_gen to version ^0.9.0
  • upgrade build_runner to version ^0.9.0

0.9.3

  • upgrade analyzer to version ^0.32.0
  • upgrade build_runner to version ^0.8.10
  • upgrade test to version ^1.0.0

0.9.2

  • upgrade sour_gen to ^0.8.0

0.9.1

  • add generics support

0.9.0

  • Add missing methods to SerializableMap

0.8.1

  • add serializable_core package

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: ${jsonEncode(p1)}'); // prints `p1: {"id":1,"name":"person 1"}`

  var p4Map = jsonDecode('{"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!`
}

Use this package as a library

1. Depend on it

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


dependencies:
  serializable: ^0.11.1

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 flutter 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.11.1 Oct 17, 2018 Go to the documentation of serializable 0.11.1 Download serializable 0.11.1 archive
0.11.0+1 Aug 7, 2018 Go to the documentation of serializable 0.11.0+1 Download serializable 0.11.0+1 archive
0.11.0 Aug 4, 2018 Go to the documentation of serializable 0.11.0 Download serializable 0.11.0 archive
0.9.3 Jun 21, 2018 Go to the documentation of serializable 0.9.3 Download serializable 0.9.3 archive
0.9.2 Apr 3, 2018 Go to the documentation of serializable 0.9.2 Download serializable 0.9.2 archive
0.9.1 Feb 28, 2018 Go to the documentation of serializable 0.9.1 Download serializable 0.9.1 archive
0.9.0 Feb 12, 2018 Go to the documentation of serializable 0.9.0 Download serializable 0.9.0 archive
0.8.1 Feb 7, 2018 Go to the documentation of serializable 0.8.1 Download serializable 0.8.1 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

All 26 versions...

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

We analyzed this package on Dec 5, 2018, and provided a score, details, and suggestions below. Analysis was completed with status completed using:

  • Dart: 2.1.0
  • pana: 0.12.7

Platforms

Detected platforms: Flutter, web, other

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

Health suggestions

Format lib/builder.dart.

Run dartfmt to format lib/builder.dart.

Format lib/serializable.dart.

Run dartfmt to format lib/serializable.dart.

Dependencies

Package Constraint Resolved Available
Direct dependencies
Dart SDK >=2.0.0-dev <3.0.0
analyzer ^0.33.0 0.33.6 0.34.0
build ^1.0.1 1.0.1
serializable_core ^0.11.1 0.11.1
source_gen ^0.9.0 0.9.1+3
Transitive dependencies
args 1.5.1
async 2.0.8
built_mirrors_core 0.10.1
charcode 1.1.2
collection 1.14.11
convert 2.0.2
crypto 2.0.6
csslib 0.14.6
dart_style 1.2.0 1.2.1
front_end 0.1.6+8 0.1.7
glob 1.1.7
html 0.13.3+3
kernel 0.3.6+8 0.3.7
logging 0.11.3+2
meta 1.1.6
package_config 1.0.5
path 1.6.2
plugin 0.2.0+3
pub_semver 1.4.2
source_span 1.4.1
string_scanner 1.0.4
typed_data 1.1.6
utf 0.9.0+5
watcher 0.9.7+10
yaml 2.1.15
Dev dependencies
build_runner ^1.0.0
build_test ^0.10.1
test ^1.0.0