在 Firebase 上设置嵌套 Map 的模型 (json_annotation.dart)

Joh*_*nal 7 dart firebase firebase-realtime-database flutter

我的 Firebase 数据库模型如下所示:

dbRef
    |___userId
             |____Cars
                  |____Alfa_Romeo
                  |             |____Year: 1992
                  |             |____Price: 10000
                  |__________Audi
                  |             |____Year: 1998
                  |             |____Price: 3000
                  |___________BMW
                                |____Year: 2001
                                |____Price: 7000
Run Code Online (Sandbox Code Playgroud)

然后我有一辆 Class Car 看起来像

import 'package:json_annotation/json_annotation.dart';


part 'car.g.dart';

/// An annotation for the code generator to know that this class needs the
/// JSON serialization logic to be generated.
@JsonSerializable()

class Car {
  Carta(this.model, this.details);

  String model;
  List details;

  factory Car.fromJson(Map<String, dynamic> json) => _$CarFromJson(json);

  Map<String, dynamic> toJson() => _$CarToJson(this);
}
Run Code Online (Sandbox Code Playgroud)

现在,当我将数据设置为 Firebase 时,我得到了这个:

dbRef
    |___userId
              |____Cars
                      |____Alfa_Romeo
                      |____Year: 1992
                      |____Price: 10000
Run Code Online (Sandbox Code Playgroud)

...我希望它像第一个图中的模型一样。如何将细节嵌套在“模型”孩子中?任何人都可以帮我解决这个问题吗?

编辑:只是为了确保我清楚我想要什么。此代码来自 Flutter Team文档示例

import 'address.dart';
import 'package:json_annotation/json_annotation.dart';
part 'user.g.dart';

@JsonSerializable(explicitToJson: true)
class User {
  String firstName;
  Address address;

  User(this.firstName, this.address);

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
  Map<String, dynamic> toJson() => _$UserToJson(this);
}
Run Code Online (Sandbox Code Playgroud)

此代码生成以下输出:

name: John, address: {street: My st., city: New York}}
Run Code Online (Sandbox Code Playgroud)

而我想要实现的是 John 成为一个 Child 键和嵌套在里面的 Adress,因为可能有多个 Adress Array。地址字段应该成为一个键(它将是唯一的),然后它将有一个项目地图,每个项目只有 2 个字段描述和价格。

Jac*_*wan 5

我建议将详细信息分解到自己的类中,如本例所示,https://flutter.dev/docs/development/data-and-backend/json#generate-code-for-nested-classes

编辑

尝试手动映射模型并将其余属性复制到另一个映射,而不是使用 JsonSerialized。

class Car {
  Car({this.model, this.details});

  String model;
  Map<String, dynamic> details;

  factory Car.fromJson(Map<String, dynamic> json) {
    Map<String, dynamic> details = Map<String, dynamic>.from(json);
    details.remove('model');

    return new Car(
      model: json['model'],
      details: details
    );
  }

  Map<String, dynamic> toJson() {
    Map<String, dynamic> json = Map<String, dynamic>.from(details);
    json['model'] = model;

    return json;
  }
}
Run Code Online (Sandbox Code Playgroud)