I need to store a Dart object from my Flutter application in Firestore
This object includes an enum property.
What is the best solution to serialize / deserialize this enum property ?
As a String
As an Int
I do not find any easy solution to do this.
1.12 Serialization of Enum Constants To serialize an enum constant, ObjectOutputStream writes the value returned by the enum constant's name method. To deserialize an enum constant, ObjectInputStream reads the constant name from the stream; the deserialized constant is then obtained by calling the java. lang. Enum.
Getting Values From a Flutter Enum All you need to do to get the value of an enum in Dart is refer to the specific property or index of the value you want. Run the code and confirm if it's printing the colors and their index according to the expected result.
Flutter is able to generate JSON serialization code. The tutorial you can find here. It references the package json_annotation. It contains also support for enum serialization. So all you need, is use this tool and annotate your enum values with @JsonValue
.
From the code docs:
An annotation used to specify how a enum value is serialized.
That's basically all. Let me now illustrate with a small example in code. Imagine an enum with vehicles:
import 'package:json_annotation/json_annotation.dart'; enum Vehicle { @JsonValue("bike") BIKE, @JsonValue("motor-bike") MOTOR_BIKE, @JsonValue("car") CAR, @JsonValue("truck") TRUCK, }
Then you can use this enum in one of your model, for example vehilce_owner.dart
that looks like this:
import 'package:json_annotation/json_annotation.dart'; part 'vehicle_owner.g.dart'; @JsonSerializable() class VehicleOwner{ final String name; final Vehicle vehicle; VehicleOwner(this.name, this.vehicle); factory VehicleOwner.fromJson(Map<String, dynamic> json) => _$VehicleOwnerFromJson(json); Map<String, dynamic> toJson() => _$VehicleOwnerToJson(this); }
This is what you need to provide according to the json generation howto. Now you need to run the builder or watcher to let flutter generate the code:
flutter pub run build_runner build
Then the generated code will look like as seen below. Take a look at the _$VehicleEnumMap
that has been generated respecting your @JsonValue
annotations:
// GENERATED CODE - DO NOT MODIFY BY HAND part of 'vehicle_owner.dart'; // ************************************************************************** // JsonSerializableGenerator // ************************************************************************** // more generated code omitted here .... const _$VehicleEnumMap = { Vehicle.BIKE: 'bike', Vehicle.MOTOR_BIKE: 'motor-bike', Vehicle.CAR: 'car', Vehicle.TRUCK: 'truck', };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With