fling_pickle 0.1.0
fling_pickle: ^0.1.0 copied to clipboard
SerDes framework for Dart.
example/example.dart
import 'package:fling_pickle/fling_pickle.dart';
// For full integration, implement the Pickleable interface and support a
// static method to create an instance from a Pickle (constructors can work, but
// you'll miss out on a few syntactic sugar features since Dart does not allow
// function pointers to constructors).
class Color implements Pickleable {
final int r;
final int g;
final int b;
const Color(final this.r, final this.g, final this.b);
@override
String toString() {
return '($r, $g, $b)';
}
//----------start Added for SerDes----------//
static Color fromPickle(final Pickle pickle) => Color(
pickle.readInt('r'),
pickle.readInt('g'),
pickle.readInt('b'),
);
@override
Pickle asPickle() {
return Pickle().withInt('r', r).withInt('g', g).withInt('b', b);
}
//----------end Added for SerDes----------//
}
// If you prefer to keep your class clean of serialization code, you can
// implement the converters separately (as long as you have access to the
// information you will need to recreate the instance). You can also convert
// recursively.
class Banana {
final String name;
final double age;
final Color favoriteColor;
final List<Color> potentialColors;
const Banana(
final this.name,
final this.age,
final this.favoriteColor,
final this.potentialColors,
);
@override
String toString() {
return '$name is $age years old and likes the color $favoriteColor out of $potentialColors';
}
}
//----------start Added for SerDes----------//
Pickle pickleBanana(final Banana banana) => Pickle()
.withString('name', banana.name)
.withDouble('age', banana.age)
.withPickleable('favoriteColor', banana.favoriteColor)
.withPickleables('potentialColors', banana.potentialColors);
Banana regurgitateBanana(final Pickle pickle) => Banana(
pickle.readString('name'),
pickle.readDouble('age'),
pickle.readPickleable('favoriteColor', Color.fromPickle),
pickle.readPickleables('potentialColors', Color.fromPickle));
//----------end Added for SerDes----------//
// Now we can serialize and deserialize an object, even one with nested
// Pickleables.
void main() async {
final fruit = Banana(
'Yellow',
1.5,
Color(255, 255, 0),
[Color(1, 2, 3), Color(4, 5, 6)],
);
print(fruit);
final pickle = pickleBanana(fruit);
final regurgitatedFruit = regurgitateBanana(pickle);
print(regurgitatedFruit);
}