Post array using http in flutter - flutter

Anyone know how to post array using http?
var headers = {"Accept": "application/json"};
var url = "https://...."
var response = await http.post(url,
body: {
....
},
I have a param named commentList. I need to pass comment[0], comment[1]... inside body.
How to use for loop inside the body???
for(var i in list){
"comments"+"["+index+"]" = i;
index ++;
}
Here the postman key and value

if you need to combine comments for specific reason you can do like this.
List commentList = ['comment1','comment2','comment3'];
Map<String, dynamic> body;
combine them:
String comments ='';
commentList.forEach((comment){
comments +=comment+' ';
});
body = {'combinedComments':comments};
then post :
var headers = {"Accept": "application/json"};
var url = "https://...."
var response = await http.post(url,
body: this.body);
or just use json encode to convert your list to string;
Map<String,dynamic> body = {'comments' :jsonEncode(commentList)};
and use this as body to post.

I managed to fix it.
int count = 0;
var url = "https://xxx";
var response = await http.post(url,
body: {
for (var i in list) 'comments[${count++}]':i,
....
},
headers: headers);

Related

Http Request Flutter didn't have body

I have a project with Flutter. And I want to get data from API. In my other project, I don't have any problem. But in this project, I have a problem. When I debug the process, in HTTP response didn't have body from API.
In class AuthService to get the API.
Future<ResponseCheckNIP> checkNIP({String? nip}) async {
var url = '$baseUrl/check-nip-new/$nip';
var header = {
'Content-Type': 'application/json',
};
// var body = jsonEncode({'nip': nip});
var response = await http.get(Uri.parse(url), headers: header);
if (response.statusCode == 200) {
var data = jsonDecode(response.body);
ResponseCheckNIP responseCheckNIP = ResponseCheckNIP.fromJson(data);
return responseCheckNIP;
} else {
throw Exception('Get NIP Failed');
}
}
And when I debug it, I get this
as we see, there is no body in there. Am I did something wrong?
If you look closely, the data is actually in the response.bodyBytes.
And Since you cannot directly convert bytes to json with dart, convert bytes to String first then decode the String using jsonDecode.
Below is the modified code.
Future<ResponseCheckNIP> checkNIP({String? nip}) async {
var url = '$baseUrl/check-nip-new/$nip';
var header = {
'Content-Type': 'application/json',
};
var response = await http.get(Uri.parse(url), headers: header);
if (response.statusCode == 200) {
// Get body bytes from response
final bytes = response.bodyBytes;
// Convert bytes to String then decode
final data = jsonDecode(utf8.decode(bytes));
ResponseCheckNIP responseCheckNIP = ResponseCheckNIP.fromJson(data);
return responseCheckNIP;
} else {
throw Exception('Get NIP Failed');
}
}
Hope this helps.
Thank you.

How to put parametrs in url with queryParamets in GET-request in dart?

I have an API and I need to put non-optional parametrs in GET-request and I did this:
Future<List<FlightBook>> fetchFlights(int mv_id) async {
String basicAuth =
'Basic ' + base64Encode(utf8.encode('$username:$password'));
print(basicAuth);
final queryParameters = {
"mv_id" : mv_id,
};
var response = await http.get(Uri.parse("http:/mylink/getFlights.php?fmt=json&{$queryParameters}" ), headers: <String, String>{'authorization': basicAuth});
var jsonResponse = convert.jsonDecode(response.body) as List;
return jsonResponse.map((e) => FlightBook.fromJson(e)).toList();
}
but when I tried to get some data from this I got the blank screen with no values and after that I did request like so and everything works fine:
'var response = await http.get(Uri.parse("http:/mylink/getFlights.php?fmt=json&mv_id=1'
How can I put this parametr inside my link if I need not only the first elemnt but all elements?
Let's try out with this
final queryParameters = {
"mv_id" : mv_id,
"fmt" : "json",
};
var uri = Uri(scheme: "http", host: "/mylink/getFlights.php", queryParameters:queryParameters );
var response = await http.get(uri, headers: <String, String>{'authorization': basicAuth});
Your string interpolation is wrong. The $ goes outside the braces.
You could do: "http:/mylink/getFlights.php?fmt=json&${queryParameters}"
But in this case, you don't need the curly braces, so I would do
"http:/mylink/getFlights.php?fmt=json&$queryParameters"
I agree with the other response on how to add the query parameters, but wanted to show why your version failed in one case and worked in the other.

Response body empty API

My response.body return empty like this: Response.body: []
It was supposed to return the param like Response.body:["CodVenda":4057}]
static Future<List<Produto>> iniciaVenda(codVenda) async {
var url = 'http://192.168.0.112:4343/inicia_venda.php';
Map<String, String> headers = {};
final params = {"CodVenda": codVenda};
print("> Params: $params");
print("> Pedido Post POST: $url");
final response = await http.post(url, body: params, headers: headers);
print('Response status: ${response.statusCode}');
print('Response body: ${response.body}');
List list = convert.json.decode(response.body);
final produtos =
list.map<Produto>((map) => Produto.fromJson(map)).toList();
var retornoResponse = false;
I get the data from a API and then I wanted to start the sell but it returns empty.
Could it be a problem in API?
Actually, you need to pass body data with JSON encoded. That may be the main problem.
final response = await http.post(url, body: jsonEncode(params), headers: headers);
You can read more from the official document.

Submit array in http flutter

This is how I post the two values to server using postman.
How should I write in http?
var url = "xxx";
var response = await http.post(url, headers: headers, body: {
....
'all_receivers': adminList.toString(),
'commence_time': endTime, // this no issue
...
});
I pass adminList which is [725,607], but get error:
Error
all_receivers id [725 is invalid. all_receivers id 607] is invalid.
You create a json and pass it
or
You can create and array of strings
You can simply resolve that by casting your List to String.
By casting the token list using toString() method you will get a String like this "['token1','token2']"
Here's the modified code:
List<String> adminList=["725","607"]; // how to pass 725,607
var response = await http.post(url, headers: headers, body: {
'all_receivers': adminList.toString(), // how to pass 725,607
}
try to pass with jsonEncode
var response = await http.post(url, headers: headers, body: JsonEncode({
'all_receivers': adminList,
});
print(response);
This is how I fixed
final receivers = adminList.join(",");
final body = {'all_receivers':receivers}
http.post(url', body: body);

How to create dynamic forms in flutter with FutureBuilder

I want to create dynamic forms and fetch data after submitted form. I have an API and I'm getting questions from this API. In application, user will answer questions and save the result to API. How can I create dynamic forms and retrieve user inputs. Please help.
FutureBuilder<List<ConditionType>>(
future: _api.getConditionTypes(job.sectorId),
builder: (context, snapshot) {
//Create Form
}
Try using json_to_form, If you could share the structure of the response I could assist to tweaking the plugin which I had to do for my own project. I should mention that with this implementation DropDownButton tends to have issues displaying values though it saves them.
I make the Json tranforms making the model of the object and then make the request:
class Model {
String projectName;
String datePlan;
String activityName;
String hours;
TimeSheetModel({this.projectName, this.datePlan, this.activityName, this.hours});
TimeSheetModel.fromJson(Map<String, dynamic> json){
projectName = json["ProjectName"];
datePlan = json["DatePlan"];
activityName = json["ActivityName"];
hours = json["Hours"];
}
Map toMap() {
var map = new Map<String, dynamic>();
map["ProjectName"] = projectName;
map["DatePlan"] = datePlan;
map["ActivityName"] = activityName;
map["Hours"] = hours;
return map;
}
}
The method fromJson transforms Json data to your object for GET request and toMap tranform your object to Json for POST or PUT request.
Making the GET request:
getProjects() async {
var url = 'url';
var res = await http
.get(Uri.encodeFull(url), headers: {"Accept": "application/json",
"charset": "UTF-8"});
data = json.decode(res.body);
setState(() {
Model data = Model.fromJson(resBody);
});
}
Making the POST request:
post() async {
var url = 'url';
http.post(url, body:
data.toMap()).then((response) {
print("Response status: ${response.statusCode}");
print("Response body: ${response.body}");
});
}