flutter await GET response is not working - flutter

i have the follow function:
Future<Null> _loadORDER(String menssage) async {
var enZona =await ApiClient.zonaNum(menssage, apiKey);
print('enZona: $enZona');
if (enZona == 'true') {
_moveToNotification(context);
};
}
the print give me the follow message: "enZona: Instance of 'Response'"
if i test the response from postman of the api query is working normally and give me: true ,
then i hope that the print result will be : "enZona: true"
but i don't know how i do to wait the response of the ApiClient before continue with the conditional (if)
thanks for your help!
thanks i add the .body but i get the same response, the apiclient code is the follow:
final response = await http.get(baseUrl + '/shop/order/$message',
headers: {HttpHeaders.authorizationHeader: apiKey});
print("enZona: $response.body");
return response;
the print value for this is: enZona: Instance of 'Response'.body

You should do print("enZona: ${response.body}"); with the curly bracket, or you can assign response.body to some variable first.
final foo = response.body; print(foo);

If you go to the pub.dev documentation for the Response class, you will see that Response is more than the content of the response. It is a wrapper class that also includes information such as the statusCode of the response, the headers, etc.
When you saw the response in Postman, you only cared about the content of the response, that is, the body of the response. What you are looking for in your code is not the enZona instance of Response, but the body of the enZona response.
Therefore, you have to swap enZona by enZona.body when trying to access the contents of your response.

Related

http.get returns 404 "Route not found"

I am trying to use a public API to search movie titles via my Flutter/Dart app.
A minimal code snippet is this
static Future<AnimeSearchResult> fetchSearchResults(String searchTerm) async {
final response = await http.get(
Uri.https("kitsu.io", "/api/edge/anime?filter[text]=cowboy%20bebop"));
// https://kitsu.io/api/edge/anime?filter[text]=cowboy%20bebop
if (response.statusCode == 200) {
// If the server did return a 200 OK response,
// then parse the JSON.
return animeSearchResultsFromMap(response.body);
} else {
// If the server did not return a 200 OK response,
// then throw an exception.
print(response.body);
throw Exception('Failed to load search results');
}
}
This will search and return an object back to a FutureBuilder Widget which then displays the results. (I have tested the UI and it is working on sample data)
Running the code, I get 404 error in my console
{"errors":[{"status":404,"title":"Route Not Found"}]}
Opening the link in my browser, it gives a JSON file as its supposed to do.
Trying to access the trending collection link using
final response = await http.get(Uri.https("kitsu.io", "/api/edge/trending/anime")); also works perfectly fine.
So I am suspecting there is some error in the way my URI is written for the search code. Precisely speaking, this line is at fault
final response = await http.get(Uri.https("kitsu.io", "/api/edge/anime?filter[text]=cowboy%20bebop"));
However I don't know what exactly is the problem.
Any help is appreciated!
Thank You!
I tried it this way, and it worked:
final response = await http.get(Uri.parse("https://kitsu.io/api/edge/anime?filter[text]=cowboy%20bebop"));
But await http.get(Uri.https resulted in the same error you are having.

Converting my Postman Call to Dart/Flutter API Call

I hope to use nutritionix api to get food information for the users of my application, I manage to get the call to work in Postman, however I cannot convert it to dart code. I am getting this error: '{message: Unexpected token " in JSON at position 0}'
Here is my (POST) postman call:
Here is my attempt at converting that to dart code:
Future<void> fetchNutritionix() async {
String url = 'https://trackapi.nutritionix.com/v2/natural/nutrients';
Map<String, String> headers = {
"Content-Type": "application/json",
"x-app-id": "5bf----",
"x-app-key": "c3c528f3a0c68-------------",
"x-remote-user-id": "0",
};
String query = 'query: chicken noodle soup';
http.Response response =
await http.post(url, headers: headers, body: query);
int statusCode = response.statusCode;
print('This is the statuscode: $statusCode');
final responseJson = json.decode(response.body);
print(responseJson);
//print('This is the API response: $responseJson');
}
Any help would be appreciated! And, again thank you!
Your postman screenshot shows x-www-form-urlencoded as the content-type, so why are you changing that to application/json in your headers? Remove the content type header (the package will add it for you) and simply pass a map to the body parameter:
var response = await http.post(
url,
headers: headers,
body: {
'query': 'chicken soup',
'brand': 'acme',
},
);
Also you can now generate Dart code (and many other languages) for your Postman request by clicking the Code button just below the Save button.
click the three dotes button in request tab and select code option then select your language that you want convert code to
review the query you're posting
your Postman input is x-www-form-urlencoded instead of plain text
String query = 'query: chicken noodle soup';
why don't you try JSON better
String query = '{ "query" : "chicken noodle soup" }';

flutter get request with parameter

I am using Client() from http.dart. I am able to post with parameter but I have no idea how to do get with parameter. Post has body that takes the parameter but get doesn't.
I have tried
This is my client
Client httpClient = Client();
var response = await httpClient.get("controller/action/{parameter here}"
I hope this should solve your problem
fetchData() async {
Client httpClient = Client();
counter++;
var response =
await httpClient.get('https://jsonplaceholder.typicode.com/photos/$counter');
print(response.body);
}
i think you are saying that you want any kind of data to be sent to the server with GET request too,
you can not do it simply,
may be your parameter are the header of the Get ,
try passing your parameters in the header of GET

Dio's get request returning incomplete data

I'm making a get request with the Dio library (https://pub.dev/packages/dio), but apparently it is not getting all the data in the coming json.
Here's the request:
This is the json that comes from it:
But this is the Response object I get from this request:
:
Note how the "headers" field in the json has substantially more values than my headers field in response.data.
Am I doing something wrong here?
You are returning response without extract it's content. That's OK, but you need to extract the body from response where you are calling this method:
http.Response response = await _yourApi.getData();
if (response.statusCode == 200) {
//Do what you want with body
final body = response.body;
}

How to directly print JSON recieved in GET Request Body in Flutter

My intention is to make a GET request using the DIO or any similar HTTP client in order to receive a JSON data/body and print it to the console.
I have written the following code to achieve that.
fetchQuestion(String userIdentifier) async {
String urlToCall =
"someURLhere";
try {
Response response = await Dio().get(
urlToCall,
options: Options(headers: {
HttpHeaders.authorizationHeader: "Bearer " + userIdentifier,
}),
);
print(response.data);
} catch (e) {
print(e);
}
}
The problem with this code is, when I print response.data, only null is printed. Even though I am certain that the response data contains a JSON file.
I have checked on the backend, and I am getting a 200 status code. Additionally, printing response.headers does print the headers I expected. It is only the response.body that prints null.
Issues I have tried include
Using print(utf8.decode(response.data));
Using json.decode(response.data) -> In which case I get
NoSuchMethodError: The getter 'length' was called on null. error.
I would appreciate any kind of help regarding printing the JSON file received.
Have you printed just response to see what fields are in there.
I haven't used DIO but http package works fine for me:
import 'package:http/http.dart' as http;
...
final response = await http.get(Url);