flutter print a single value from json api - flutter

i am new to flutter and want to print only my name
my code is below i tryed but i am getting error
var resBody = await http.post(
my_url,
headers: header,
);
print(resBody.body);
i get data like this
[{name:hari,age:26,sex:male}]
i want to print name only i tryed like this but it does not work i dont know whats wrong here
print(resBody.body.name);
i getiing error
how do i print any data like that

You can access the data using key of the json object try this
var resBody = await http.post(
my_url,
headers: header,
);
final data=jsonDecode(resBody.body)//Parses the string and returns the resulting Json object
print(data[0]["name"]

Try below code,and used jsonDecode(resBody.body)['name'] jsonDecode
var resBody = await http.post(
my_url,
headers: header,
);
final jsonData=jsonDecode(resBody.body)['name'];//it prints only name of your json string
print(jsonData);

Related

Bad status code response from MultipartRequest

does anyone have any idea what could be wrong because I have no idea what could be causing the error?
When I'm connecting with my Rest Api where I have to put some String data and also 1 File by PostMan like in picture below:
https://files.fm/f/vrxe9zsnu
it all works how it shoud. I mean that it create new order in DB with BLOB and datas but then I'm trying doing this same on Mobile App project Idk why I'm getting respone status code 208 with message
{"timestamp":1647283779156,"message":"could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"}
I'm sending there File which I get from ImagePicker library.
Future<String> multipart(File imageFile) async {
var request = http.MultipartRequest(
'POST', Uri.parse(ApiHeadersInfo().createNewOrderUrl));
request.headers.addAll({
"Authorization": "Bearer eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJwcEBnbWFpbC5jb20iLCJleHAiOjE2NDgyODIxNjR9.ZYOo2g1iexKZynpdoIkCMbsxzHhwLDNZEIj9qUlZj2GcwqLtUTcxaBS49_xPkewg-i22eKkGNjIQAMtjw5vwIQ",
"Content-type": "multipart/form-data"
});
request.files.add(await http.MultipartFile.fromPath('multipartFile', imageFile.path));
request.fields['customer'] = "newOrder.customer";
request.fields['loadingCompanyName'] = "newOrder.loadingCompanyName";
request.fields['loadingCity'] = "newOrder.loadingCity";
request.fields['loadingPostcode'] = "newOrder.loadingPostcode";
request.fields['dateOfLoading'] = "newOrder.dateOfLoading";
request.fields['unloadingCompanyName'] = "newOrder.unloadingCompanyName";
request.fields['unloadingPostcode'] = "newOrder.unloadingPostcode";
request.fields['dateOfUnloading'] = "newOrder.dateOfUnloading";
request.fields['nettoPrice'] = '11.0';
request.fields['bruttoPrice'] = '11.0';
request.fields['information'] = "newOrder.information";
http.Response response = await http.Response.fromStream(await request.send());
print("Result: ${response.statusCode}");
print("fields: ${request.fields}");
return response.body;
}
Any ideas what is wrong here? Maybe bad http request method I just use for it ?
Have completely no idea.
Many thanks.

How to retrieve/decode json/map from downloaded ByteStream?

I have a ByteStream downloaded from a Server, namely datas regarding the user.
Its in MySql server as
"username":"Neor","totalCoins":"350"
The truncated part of .php file that gives-away this data, is as follows:
$data = $stmt->fetchColumn();
header($_SERVER["SERVER_PROTOCOL"] . " 200 OK");
header("Cache-Control: public");
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-Length:".strlen($data));
echo $data;
I use ths Flutter code to download the data:
Future<void> downloadData() async {
var url = Uri.parse("https://example.com/mycloud.php");
var request = http.MultipartRequest('POST', url)
..fields["user"] = "Dia";
var response = await request.send();
var stream = response.stream; }
On checking if the downloaded ByteStream contains anything, I've used print(stream.length), which prints out as 137.
How can I get the information I want from the ByteStream?
(If my question lacks in any way, please let me know.)
There shouldn't be any need to use a multipart request for a simple POST. Instead use the simpler http.post method.
Future<void> downloadData() async {
final response = await http.post(
Uri.parse('https://example.com/mycloud.php'),
body: <String, String>{
'user': 'Dia',
},
);
final decodedJson = json.decode(response.body);
// if you want to ensure the character set used, replace this with:
// json.decode(utf8.decode(response.bodyBytes));
}
If you do stick with the stream way, you have a Stream<List<int>> that you want to turn initially into a List<int>. Use the toList() method on stream for that. Then you have to decode that into characters. JSON is always encoded in utf8, so you could:
json.decode(utf8.decode(await stream.toList()));
(Under the hood, http is basically doing that for you; collecting the stream together and doing the character decoding and presenting that as body.)
First
import 'dart:convert' show utf8;
String foo = utf8.decode(bytes);
Then
Map valueMap = json.decode(foo );

http.get causes Japanese text to get jumbled

I am using following code to get data from a server that has Japanese text.
final response = await http.get(url, headers: {
'Content-Type': 'application/json',
});
I get the data correctly but all the Japanese text does not look correct. They look like
æ±äº¬éƒ½ä¸­å¤®åŒºæ—¥æœ¬æ©‹å®¤ç”º3-3-9
When I use "Postman" to check the data, it is displaying Japanese text correctly.
How do I get around this issue?
I have the same problem when I put the values.
I use;
Map<String, String> headers = {
'Content-Type': 'application/json',
'authorization': basicAuth,
};
final msg = jsonEncode(data);
final response = await http.put(
url,
headers: headers,
body: msg,
);
The data does not seems to encode correctly, when they are in Japanese.
Can someone provide some help on this ?

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" }';

How send data to php file With Post

I am new in flutter and I want to send data(id in my program) to a php file and get it with $_POST ,and then send the result back but the Solution's that i have found didn't work .
I think my body is wrong , I tried to change body to a
Map<String,dynamic>
but its didn't work.
Future<List<dynamic>> getData() async {
String body = "{'id' : 1}" ;
String url = "http://10.0.2.2:8080/facts/get.php";
http.Response responseData = await http.post(
url
,body: body);
print(responseData.body);
return json.decode(responseData.body);
}