我正在尝试创建一个方法,该方法采用类型为Suburb
的对象并将其强类型写入Firestore。该对象深深地嵌套在我的数据模型中。这是在json序列化程序生成器的帮助下创建的我的数据模型。
import 'package:json_annotation/json_annotation.dart';
part 'voter_data.g.dart';
@JsonSerializable(explicitToJson: true)
class VoterData {
VoterData({this.voterId,this.screenState, this.location});
@JsonKey(name: 'voter_id')
final String voterId;
final int screenState;
final Location location;
factory VoterData.fromJson(Map<String, dynamic> json) =>
_$VoterDataFromJson(json);
Map<String, dynamic> toJson() => _$VoterDataToJson(this);
}
@JsonSerializable()
class Location {
final Suburb suburb;
final Postcode postcode;
final Country country;
Location({this.suburb, this.country, this.postcode});
factory Location.fromJson(Map<String, dynamic> json) =>
_$LocationFromJson(json);
Map<String, dynamic> toJson() => _$LocationToJson(this);
}
@JsonSerializable()
class Suburb {
String code;
String name;
Suburb({
this.code,
this.name,
});
factory Suburb.fromJson(Map<String, dynamic> json) =>
_$SuburbFromJson(json);
Map<String, dynamic> toJson() => _$SuburbToJson(this);
}
@JsonSerializable()
class Postcode {
String code;
String name;
Postcode({
this.code,
this.name,
});
factory Postcode.fromJson(Map<String, dynamic> json) =>
_$PostcodeFromJson(json);
Map<String, dynamic> toJson() => _$PostcodeToJson(this);
}
@JsonSerializable()
class Country {
String code;
String name;
Country({
this.code,
this.name,
});
factory Country.fromJson(Map<String, dynamic> json) =>
_$CountryFromJson(json);
Map<String, dynamic> toJson() => _$CountryToJson(this);
}
这是方法:
setSuburb(Suburb suburb)async{
VoterData voterData= VoterData();
final path = '/voters/$uid/';
final documentReference = Firestore.instance.document(path);
await documentReference.setData(voterData.location.suburb.toJson(), merge: true);
}
这将不起作用,因为方法参数中的郊区与setData方法中的郊区不同。编写该方法的最佳方法是什么? (在代码中,一个api调用返回一个我想在该方法中弹出并保存到Firestore的郊区。)
它在Firestore中的外观: