我有这个模型
class Trail {
List<CusomPosition> markers;
List<Vote> voteList;
...}
我已经定义了表决和CustomPosition。所有这些类都具有@JsonSerializable批注,并且是它们各自的部分'class.g.dart'的一部分;文件。
当我运行命令时:
flutter pub run build_runner build
一切正常,但是当我尝试在Firestore上添加实例时
Firestore.instance.collection("trails").add(finalTrail.toJson());
我收到此错误:
Unhandled Exception: Invalid argument: Instance of 'Vote'
如果我打印finalTrail.toJson(),我会得到:
votesList: [Instance of 'Vote']
我该怎么做才能正确转换它?
编辑:这是我的足迹的一部分。g.dart
markers: (json['markers'] as List)
?.map((e) => e == null
? null
: CustomPosition.fromJson(e as Map<String, dynamic>))
?.toList(),
votesList: (json['votesList'] as List)
?.map((e) =>
e == null ? null : Vote.fromJson(e as Map<String, dynamic>))
?.toList(),
Vote.fromJson和CustomPosition.fromJson都存在(它们是通过运行命令创建的)
答案 0 :(得分:0)
也许此代码可以为您提供帮助?
import 'dart:convert';
import 'json_objects.dart';
void main() {
var json = jsonDecode(_data) as Map<String, dynamic>;
var finalTrail = Trail.fromJson(json);
print(finalTrail.markers[0].myPosition);
print(finalTrail.voteList[0].myVote);
// Firestore.instance.collection("trails").add(finalTrail.toJson());
print(finalTrail.toJson());
}
var _data = '{"markers":[{"myPosition":1}],"voteList":[{"myVote":41}]}';
1 41 {markers: [{myPosition: 1}], voteList: [{myVote: 41}]}
JSON数据模型:
class CustomPosition {
final int myPosition;
CustomPosition({this.myPosition});
factory CustomPosition.fromJson(Map<String, dynamic> json) {
return CustomPosition(
myPosition: json['myPosition'] as int,
);
}
Map<String, dynamic> toJson() {
return {
'myPosition': myPosition,
};
}
}
class Trail {
final List<CustomPosition> markers;
final List<Vote> voteList;
Trail({this.markers, this.voteList});
factory Trail.fromJson(Map<String, dynamic> json) {
return Trail(
markers:
_toObjectList(json['markers'], (e) => CustomPosition.fromJson(e)),
voteList: _toObjectList(json['voteList'], (e) => Vote.fromJson(e)),
);
}
Map<String, dynamic> toJson() {
return {
'markers': _fromList(markers, (e) => e.toJson()),
'voteList': _fromList(voteList, (e) => e.toJson()),
};
}
}
class Vote {
final int myVote;
Vote({this.myVote});
factory Vote.fromJson(Map<String, dynamic> json) {
return Vote(
myVote: json['myVote'] as int,
);
}
Map<String, dynamic> toJson() {
return {
'myVote': myVote,
};
}
}
List _fromList(data, Function(dynamic) toJson) {
if (data == null) {
return null;
}
var result = [];
for (var element in data) {
var value;
if (element != null) {
value = toJson(element);
}
result.add(value);
}
return result;
}
List<T> _toObjectList<T>(data, T Function(Map<String, dynamic>) fromJson) {
if (data == null) {
return null;
}
var result = <T>[];
for (var element in data) {
T value;
if (element != null) {
value = fromJson(element as Map<String, dynamic>);
}
result.add(value);
}
return result;
}
/*
Trail:
markers: List<CustomPosition>
voteList: List<Vote>
CustomPosition:
myPosition: int
Vote:
myVote: int
*/