我正在尝试访问 API,然后将其存储到模型中?API 响应相当长,由多级键值对组成。我打的 API 是https://gharsansar-backend.herokuapp.com/listing/get/all。这将返回数据库中一些属性的列表。我在 Flutter 中制作的模型是:
class Listing {
Map property;
Map listedby;
int listPrice;
int featured;
String status;
String id;
String listType;
String listingTitle;
String listingSlug;
String contactNumber;
String specialNote;
String listPriceUnit;
String numOfViewers;
Map viewers;
Map favouriteOf;
Listing();
Listing.fromJSON(Map<String, dynamic> jsonMap) {
print(jsonMap);
try {
property = jsonMap['property'] != null ? jsonMap['property'] : '';
listedby = jsonMap['listedby'] != null ? jsonMap['listedby'] : '';
id = jsonMap['_id'] != null ? jsonMap['_id'] : '';
listPrice = jsonMap['listPrice'] != null ? jsonMap['listPrice'] : '';
listType = jsonMap['listType'] != null ? jsonMap['listType'] : '';
featured = jsonMap['featured'] != null ? jsonMap['featured'] : '';
favouriteOf =
jsonMap['favouriteOf'] != null ? jsonMap['favouriteOf'] : '';
viewers = jsonMap['viewers'] != null ? jsonMap['viewers'] : '';
listingTitle =
jsonMap['listingTitle'] != null ? jsonMap['listingTitle'] : '';
listingSlug =
jsonMap['listingSlug'] != null ? jsonMap['listingSlug'] : '';
status = jsonMap['status'] != null ? jsonMap['status'] : '';
contactNumber =
jsonMap['contactNumber'] != null ? jsonMap['contactNumber'] : '';
specialNote =
jsonMap['specialNote'] != null ? jsonMap['specialNote'] : '';
listPriceUnit =
jsonMap['listPriceUnit'] != null ? jsonMap['listPriceUnit'] : '';
numOfViewers =
jsonMap['numOfViewers'] != null ? jsonMap['numOfViewers'] : '';
} catch (e) {
print(e);
}
}
Map toMap() {
var map = new Map<String, dynamic>();
map["property"] = property;
map["listedby"] = listedby;
map["_id"] = id;
map["listPrice"] = listPrice;
map["listType"] = listType;
map["contactNumber"] = contactNumber;
map["favouriteOf"] = favouriteOf;
map["viewers"] = viewers;
map["listingTitle"] = listingTitle;
map["listingSlug"] = listingSlug;
map["status"] = status;
map["specialNote"] = specialNote;
map["listPriceUnit"] = listPriceUnit;
map["numOfViewers"] = numOfViewers;
return map;
}
@override
String toString() {
var map = this.toMap();
return map.toString();
}
}
我正在使用以下代码从颤振中获取 API:
Future<Stream<Listing>> getProperties() async {
Uri uri = Helper.getUri('listing/get/all');
print(uri.toString());
Map<String, dynamic> _queryParams = {};
uri = uri.replace(queryParameters: _queryParams);
final client = new http.Client();
final streamedRest = await client.send(http.Request('get', uri));
return streamedRest.stream
.transform(utf8.decoder)
.transform(json.decoder)
.map((data) => Helper.getListings(data))
.expand((data) => (data as List))
.map((data) => Listing.fromJSON(data));
}