Can't access Nested array object flutter - flutter

I have set of data, with some details,when i try to display the the one value returns null,other 2 data is fine,but if i try to show other data it's shows null,if i try to add that to setState,everything become null,There is no problem when i get the "Description","imagepath" i can show it, but the data from the replys object doesn't show
JSON
{
"doc": {
"image": {
"Description": "tested",
"replay": " ",
"Image_Rating": 0,
"replay_status": 0,
"Report_Date": "1591228800",
"Status": 1,
"_id": "5ed88ae73025a4445568ece3",
"image_path": "http://xxx.xxx.xxx.xxx:xxx/area_images/1670281356001.jpg",
"Created_User_Id": "5ed22c2507a33e2c1cf3a3a5",
"Branch_Id": "5ed22bf807a33e2c1cf3a3a4",
"image_temp_path": "http://xxx.xxx.xxx.xxx:xxx/area_images_temp/1670281356001.jpg",
"Order_Id": 32425,
"reg_date": "1591249638163",
"Area_Id": "5dc11c4046c214298f85e2e0",
"Section_Id": "5dc1097546c214298f85e2ae",
"Report_Time_Type": 1,
"mapperId": "5ed22c4207a33e2c1cf3a3a6",
"Created_At": "Thursday, June 4th, 2020, 11:17:18 AM",
"__v": 0
},
"replays": [
{
"replay": "Good\n",
"Report_Date": "1590796800",
"_id": "5ed248e0c1a47a3e8c4ce8bb"
}
]
}
}
Code
Future<String> getImageView(String imageid) async {
Future token = SharedPrefrence().getToken();
token.then((data) async {
var token = data;
var response = await http.post(Urls.Image_Details,
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer $token",
},
body: json.encode({
"imageId": imageid,
}));
if (response.statusCode == 200) {
try {
var resp = response.body;
Map<String, dynamic> value = json.decode(resp);
var name = value['doc']['image'];
Description = name["Description"].toString();
image_path = name["image_path"].toString();
replay = name["replays"]["replay"].toString();
setState(() {
Description = name["Description"].toString();
image_path = name["image_path"].toString();
// replay = name["replays"]["replay"].toString();
});
} catch (e) {
e.toString();
}
}
});
}

"replays" is an array. Try this: name["replays"][0]["replay"].toString()
By adding [0] it will get your first object from that array.
EDIT:
After looking at your json some more I see that name is the wrong object.
"replays" is a member of "doc" not of "image".
I think this should work:
replay = value['doc']["replays"][0]["replay"].toString();

The problem is
"replays": [
{
"replay": "Good\n",
"Report_Date": "1590796800",
"_id": "5ed248e0c1a47a3e8c4ce8bb"
}
]
This is a List of Maps. So as we access the first element in the list you should use
replay= value['doc']["replays"][0]["replay"].toString();
that is the zeroth element of the list.

Related

What is the correct way to hit the API in GetX?

I am using Getx GetConnect() to hit the API. But most of the time GetConnect() is not hitting the API. I am not sure what is going wrong.
This is my code :
Response response = await GetConnect().post(
apiBaseUrl + taskPathApi + getV2,
{
"query": {
"tasker_id": kTaskerId,
"task_status": [13],
"tasker_availability": ["Checking", "Yes", "No"]
},
"display": {
"perpage": 3,
"pageno": pageNumber,
"sorting_task": "start_asc"
},
},
headers: {
"accept-language": kLanguageCode.value,
},
);
if (response.statusCode == 200) {
status = TaskList.fromJson(response.body).status;
if (status) {
totalCount = TaskList.fromJson(response.body).data.count;
taskList.addAll(TaskList.fromJson(response.body).data.tasks);
pageLoading = false.obs;
refreshRequestedTask.loadComplete();
update();
}
} else {
print("Something went wrong");
refreshRequestedTask.loadComplete();
}
Is this the proper way to use GetConnect() ? or I am doing something wrong ?
Here is the full example of GetX API call example
https://github.com/dhola-hardik/flutter_getx_example.git

Add array via Cloud Firestore REST API

I am trying to send data to FireStore form Airtable by using Firestore REST API, and I am stack with sending an array. I get the array as a string in Firestore. But the outcome should be with Housekeeping and Transportation tags as separate items of the array.
const createTagsArr = (arr) => { let r = []; arr.forEach(obj => r.push(obj.name)); return r}
for (let i = 0; i < query.records.length; i++) {
if (query.records[i].getCellValueAsString("approved")) {
let obj = {
"fullDescription": query.records[i].getCellValueAsString("fullDescription"),
"tags": createTagsArr(query.records[i].getCellValue("tags").filter(obj => obj.name)),
"id": query.records[i].getCellValueAsString("initialForm"),
}
arr.push(obj)
}
}
const pushData = async () => {
for (let i = 0; i < arr.length; i++) {
let data = {
fullDescription: { stringValue: arr[i].fullDescription },
tags: { arrayValue: {values: [{stringValue: JSON.stringify(arr[i].tags)}]} },
let response = await fetch(`https://firestore.googleapis.com/v1/projects/{project-name}/databases/(default)/documents/{coolection}/${arr[i].id}?updateMask.fieldPaths=fullDescription&updateMask.fieldPaths=tags`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + token
},
body: JSON.stringify({ "fields": data })
})
console.log(response)
}
}
const init = async () => {
console.log(providersArr)
await pushData()
}
init()
If I remove JSON.stringify() from this line:
tags: { arrayValue: {values: [{stringValue: JSON.stringify(providersArr[i].tags)}]} }
I am getting bad request error.
I would appreciate any help. Thank you!
Each value of an array must have a key of stringValue. To be able to separate the values of arr[i].tags, you should first iterate your arr[i].tags, construct the object and push it in an array. See sample code below:
const pushData = async () => {
for (let i = 0; i < arr.length; i++) {
// Initiate an empty array.
let tags = [];
// Iterate the `arr[i].tags` to create an array of objects.
for (const tag of arr[i].tags) {
// Construct the object to be pushed in the initialized array.
tags.push({ stringValue: tag });
}
let data = {
fullDescription: { stringValue: arr[i].fullDescription },
// Use the created array here.
tags: { arrayValue: {values: tags} },
}
let response = await fetch(`https://firestore.googleapis.com/v1/projects/{project-name}/databases/(default)/documents/{collection}/${arr[i].id}?updateMask.fieldPaths=fullDescription&updateMask.fieldPaths=tags`, {
method: "PATCH",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + token
},
body: JSON.stringify({ "fields": data })
})
console.log(response)
}
}
The code above will result to:
For more information, you may check out these documentation:
Value
ArrayValue

SafeSearch (Google Cloud API) request not returning anything in flutter app

When users upload a photo in my flutter app I want to call the function below to flag inappropriate images. I first upload the image to firebase storage then call this function using the generated image URL. For now, I just want it to print the results to make sure it works but nothing is printed.
static void isAppropriate(String url) async {
const String safeSearchURl =
"https://vision.googleapis.com/v1/images:annotate";
const apiKey = "HIDDEN";
var headers = {
'Content-Type': 'application/json',
'Authorization': 'key=$apiKey'
};
var request = http.Request('POST', Uri.parse(safeSearchURl));
request.body = '''
{
"requests": [
{
"image": {
"source": {
"imageUri": "$url"
}
},
"features": [
{
"type": "SAFE_SEARCH_DETECTION"
}
]
}
]
}''';
request.headers.addAll(headers);
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
} else {
print(response.reasonPhrase);
}
}
}
This is an example of what the printed response should be:
{
"responses": [
{
"safeSearchAnnotation": {
"adult": "UNLIKELY",
"spoof": "VERY_UNLIKELY",
"medical": "VERY_UNLIKELY",
"violence": "LIKELY",
"racy": "POSSIBLE"
}
}
]
}

How to receive the response of a POST request using flutter

I am new to flutter and am trying to receive a response that is returned when I do a post request. I want to display the response object in a preview modal however, i am stuck on how to go about it. I have so far been able to hit the post endpoint successfully and a console.log shows me the response as I expected. How can I receive the response and assign it to a variable that I can then pass to a view modal?
Here is what I have done so far:
/* The Post DbRequest */
Future < Reservation ? > priceReservation(Reservation priceReservation) async {
var content = jsonEncode(priceReservation.toJson());
const baseUrl = ApiEndPoint.baseUrl;
searchUrl = '$baseUrl/reservation/price';
var response = await http.post(
Uri.parse(searchUrl),
body: content,
headers: {
"Content-Type": "application/json"
},
);
final data = json.decode(response.body);
if (response.statusCode == 202) {
print(data);
return data;
} else
print(data);
return null;
}
/* The Post Service */
priceReservation(priceReservation) async {
ReservationDbRequests requests = ReservationDbRequests();
Reservation ? reservation =
await requests.priceReservation(priceReservation);
return reservation;
}
/* How can I receive the response in this save method and assign it the data variable */
_save() async {
if (_formKeyBooking.currentState!.validate()) {
Reservation reservationObject = new Reservation(
roomId: _roomController.text,
email: _emailController.text,
quantity: _quantityController.text.toString(),
checkInDate: DateTime.parse(_checkInController.text),
checkOutDate: DateTime.parse(_checkOutController.text),
);
Response data = await Provider.of < BookingService > (context, listen: false)
.priceReservation(reservationObject);
print(data);
setState(() {
_isLoading = false;
});
toastMessage(ToasterService.successMsg);
} else {
toastMessage(ToasterService.errorMsg);
}
}
// Here is my response
{
"id": "c204b78b-cae3-44ea-9aaf-2f439488fef9",
"email": "adeleke#email.com",
"quantity": 1,
"nights": 5,
"totalPricePerRoomPerNight": 134.07,
"totalPrice": {
"rooms": 615.0,
"discounts": 0.0,
"taxes": 55.35,
"total": 670.35
},
"room": {
"id": "d54986a8-4e00-4332-8edc-acf6e380f6c4",
"name": "villa",
"price": 123.0
},
"checkInDate": "2021-09-29T12:00:00+03:00",
"checkOutDate": "2021-10-04T12:00:00+03:00",
"taxes": [
{
"name": "room services",
"percent": 9.0,
"amount": 11.07
}
],
"discounts": []
}
will this help? check this artilcle for json serilization for complex response
Future <Map<String,dynamic>?> priceReservation(Reservation priceReservation) async {
//you API access code goes here
//check the status first before decoding
if (response.statusCode == 200) { //got the response with data
return json.decode(response.body);
} else if (response.statusCode == 204) { //got the response but no data
return null;
} else { //throw exception for other status code
throw 'error';
}
}
/* The Post Service */
Future<Map<String,dynamic>?> priceReservation(priceReservation) async {
ReservationDbRequests requests = ReservationDbRequests();
Map<String,dynamic>? response =
await requests.priceReservation(priceReservation);
return response;
}
//view
Map<String,dynamic>?> response = await Provider.of < BookingService > (context, listen: false)
.priceReservation(reservationObject);
print(response); //now it should be a Map
if(response != null){
print(response); //all response
print(response['id']); //access id
print(response['email']); //access email
print(response['room']['name']); //access room name
}

Flutter: Parsing JSON array

I'm trying out http requests from flutter to my backend.
My JSON is like this:
"_hits": {
"Do8HpM3w0mh99SF": {
"docid": "Do8HpM3w0mh99SF"
},
"HNLvkccTCIlmrcQ": {
"docid": "HNLvkccTCIlmrcQ"
},
"QNSInDU2BJMF5SD": {
"docid": "QNSInDU2BJMF5SD"
},
"UVDfRueZXIVCssk": {
"docid": "UVDfRueZXIVCssk"
},
"Y9bNKklTr2Sg6Ai": {
"docid": "Y9bNKklTr2Sg6Ai"
},
"kJgwwMbgF6PBwmMJSiKC": {
"docid": "kJgwwMbgF6PBwmMJSiKC"
},
"py5MbGK11SsbXQ1": {
"docid": "py5MbGK11SsbXQ1"
}
}
My code to request:
Future<SearchResults> fetchJson() async {
final response =
await http.get('MyWebsite.com');
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
// print(response.body);
return SearchResults.fromJson(json.decode(response.body));
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
throw Exception('Failed to load request');
}
}
The Search Results Class:
class SearchResults {
final String hits;
SearchResults({this.hits});
factory SearchResults.fromJson(Map<String, dynamic> json) {
return SearchResults(
hits: json['_hits'],
);
}
}
What I'm trying to achieve:
Print the value of docid under the array of _hits
Coming From iOS Swift, this is very new to me, any input is greatly appreciated.
Your SearchResuts object is wrong as _hits is not a String but a Map<String, dynamic> to do it simple :
class SearchResults {
Map<String, dynamic> hHits;
SearchResults({this.hHits});
SearchResults.fromJson(Map<String, dynamic> json) {
hHits = json['_hits'];
}
}
From here, you can iterate on your docids by getting a list of _hits elements like this :
print(searchResults.hHits.values.toList());
will print
[{docid: Do8HpM3w0mh99SF}, {docid: HNLvkccTCIlmrcQ}, {docid: QNSInDU2BJMF5SD}, {docid: UVDfRueZXIVCssk}, {docid: Y9bNKklTr2Sg6Ai}, {docid: kJgwwMbgF6PBwmMJSiKC}, {docid: py5MbGK11SsbXQ1}]