作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
我需要将我的 Flutter 应用程序中的 Dart 对象存储在 Firestore 中
这个对象包含一个枚举属性。
序列化/反序列化此枚举属性的最佳解决方案是什么?
作为一个字符串
作为一个整数
我没有找到任何简单的解决方案来做到这一点。
最佳答案
Flutter 能够生成 JSON 序列化代码。教程你可以找here .它引用包 json_annotation .它还包含对枚举序列化的支持。因此,您所需要的就是使用此工具并使用 @JsonValue
注释您的枚举值。
来自code docs :
An annotation used to specify how a enum value is serialized.
基本上就这些了。现在让我用代码中的一个小例子来说明。想象一个包含车辆的枚举:
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
然后生成的代码将如下所示。查看根据您的 @JsonValue
注释生成的 _$VehicleEnumMap
:
// 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/
我是一名优秀的程序员,十分优秀!