How to manage serialize / deserialize an enum property with Dart / Flutter to Firestore?

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',
};

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)