我从服务器收到以下API响应
{
_embedded: [
{
_id: {
$oid: "5e26c4d32c9da790ea1c4b7a"
},
storeName: "ggagav",
phone: "+919654846950",
pincode: "ahhahbba",
area: "qhhahs",
city: "whahhw",
state: "whahhw",
_etag: {
$oid: "5e26c4d3462ceb46c79b7439"
}
},
{
_id: {
$oid: "5e26c48f2c9da790ea1c4b67"
},
storeName: "gggg",
phone: "+919654846440",
pincode: "161161",
area: "gvqvvavav",
city: "vavavav",
state: "qvavava",
_etag: {
$oid: "5e26c48f462ceb46c79b7438"
}
},
{
_id: {
$oid: "5e26c1152c9da790ea1c4add"
},
storeName: "rajprakash",
phone: "+919654846230",
pincode: "shshsbs",
area: "hshsbsba",
city: "ahahshhs",
state: "shshsbs",
_etag: {
$oid: "5e26c115462ceb46c79b7437"
}
}
],
_id: "stores",
_returned: 5
}
我想知道在函数中提供电话号码时如何获取任何元素的oid。
我可以通过以下请求获取Api信息
Future<Stores> getStore() async {
try {
Response response = await _dio.get(_endPoint, options: Options(
headers: <String, String>{'authorization': _b},
)
);
if(response.statusCode == 200){
print(response.data);
return Stores.fromJson(response.data);}else{return null;}
} catch (error, stacktrace) {
print("Exception occured: $error stackTrace: $stacktrace");
return (error);
}
}
并且我只想显示具有选定电话号码的商店
Future <Stores> getStoresData() async{
final r = await _repository.getStores();
return r;
}
在此,r提供整个响应。如何从响应数据中选择特定的商店。
答案 0 :(得分:1)
您应该只为一个商店创建一个类,然后将JSON数组中的所有商店添加到类型为List的变量中。然后,您可以使用以下代码。
String getOidFromPhoneNumber(List<Store> stores, String phoneNumber) {
Store store = stores.firstWhere((store) => store.number == phoneNumber);
return store.id ?? "No store matching with that phone number";
}