我需要将Flutter应用程序中的Dart对象存储在Firestore中

该对象包含一个枚举属性。

将此枚举属性序列化/反序列化的最佳解决方案是什么?

  • 作为字符串
  • 作为Int

  • 我找不到任何简单的解决方案来做到这一点。

    最佳答案

    Flutter能够生成JSON序列化代码。您可以在本教程中找到here。它引用了json_annotation包。它还包含对枚举序列化的支持。因此,您所需要的就是使用此工具,并用@JsonValue注释您的枚举值。

    code docs:



    基本上就是全部。现在让我用一个小例子来说明代码。想象一下一个载具的枚举:

    import 'package:json_annotation/json_annotation.dart';
    
    enum Vehicle {
      @JsonValue("bike") BIKE,
      @JsonValue("motor-bike") MOTOR_BIKE,
      @JsonValue("car") CAR,
      @JsonValue("truck") TRUCK,
    }
    

    然后,您可以在您的模型之一中使用此枚举,例如vehilce_owner.dart如下所示:

    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);
    }
    

    这是您需要根据json generation howto提供的内容。现在,您需要运行构建器或watcher,以使flutter生成代码:

    flutter pub run build_runner build
    

    然后,生成的代码将如下所示。查看关于_$VehicleEnumMap批注的已生成的@JsonValue:

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

    关于enums - 如何使用Dart/Flutter到Firestore来管理枚举属性的序列化/反序列化?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53035817/

    10-12 12:20
    查看更多