我试图对我的类进行编码,以便将一个put http发送到firebase,但是当我打印User.toMap时,我的函数显示了一个带有"Instance of 'Address'“的列表。
{id: -LVsaRJKo3vo6q9NWZn_, name: User 38197, email: null, address: [Instance of 'Address']}class User {
String id;
String name;
String email;
List<Address> address = new List<Address>();
User({this.id, this.name, this.email, this.address});
User.fromMap(Map<String, dynamic> map) {
this.id = map['id'];
this.name = map['name'];
this.email = map['email'];
if (map['address'] == null) {
this.address = new List<Address>();
} else {
this.address= (map['address'] as List).map((i) => Address.fromMap(i)).toList();
}
}
Map<String, dynamic> toMap() {
return {'id': id, 'name': name, 'email': email, 'address': address};
}
}===
class Address {
String test;
Address ({this.test});
Address.fromMap(Map<String, dynamic> map) {
this.test = map['test'];
}
Map<String, dynamic> toMap() {
return {
'test': test
}
}===
在类ApiProvider中
Future<User> updateUser(User userUpdate) async {
String id = userUpdate.id;
print(userUpdate.toMap()); // This prints that line
final http.Response response = await http.put(
baseUrl + '/user/$id.json',
body: json.encode(userUpdate.toMap()), // Here happens the error
);
final Map<String, dynamic> userData = json.decode(response.body);
User user = new User.fromMap(userData);
return user;
}===
最后一个错误:
I/flutter (17495): {id: -LVsaRJKo3vo6q9NWZn_, name: User 38197, email: null, address: [Instance of 'Address']}
E/flutter (17495): [ERROR:flutter/shell/common/shell.cc(184)] Dart Error: Unhandled exception:
E/flutter (17495): Converting object to an encodable object failed: Instance of 'Address'
E/flutter (17495): #0 _JsonStringifier.writeObject (dart:convert/json.dart:703:7)
E/flutter (17495): #1 _JsonStringifier.writeList (dart:convert/json.dart:753:7)
E/flutter (17495): #2 _JsonStringifier.writeJsonValue (dart:convert/json.dart:735:7)
E/flutter (17495): #3 _JsonStringifier.writeObject (dart:convert/json.dart:693:9)
E/flutter (17495): #4 _JsonStringifier.writeMap (dart:convert/json.dart:786:7)
E/flutter (17495): #5 _JsonStringifier.writeJsonValue (dart:convert/json.dart:741:21)
E/flutter (17495): #6 _JsonStringifier.writeObject (dart:convert/json.dart:693:9)发布于 2019-01-15 00:22:15
Map<String, dynamic> toMap() {
return {'id': id, 'name': name, 'email': email, 'address': address};
}需要更改为
Map<String, dynamic> toMap() {
return {'id': id, 'name': name, 'email': email, 'address': address.map((a) => a.toMap()).toList()};
}https://stackoverflow.com/questions/54184952
复制相似问题