Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save swissonid/b8ffc39ed1095222141f928e301e0d42 to your computer and use it in GitHub Desktop.
Save swissonid/b8ffc39ed1095222141f928e301e0d42 to your computer and use it in GitHub Desktop.
Plugin for built_value to serialize the timestamp for firebase
import 'package:built_value/serializer.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
class FirebaseTimestampSerializerPlugin implements SerializerPlugin {
@override
Object beforeSerialize(Object object, FullType specifiedType) {
if (object is DateTime && specifiedType.root == DateTime)
return object.toUtc(); //Timestamp.fromMicrosecondsSinceEpoch(object);
return object;
}
@override
Object afterSerialize(Object object, FullType specifiedType) {
if (specifiedType.root == DateTime)
return Timestamp.fromMicrosecondsSinceEpoch(object);
return object;
}
@override
Object beforeDeserialize(Object object, FullType specifiedType) {
if (object is Timestamp && specifiedType.root == DateTime) {
return object.microsecondsSinceEpoch;
}
return object;
}
@override
Object afterDeserialize(Object object, FullType specifiedType) {
return object;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment