Flutter: How to sent an array to post request API? - arrays

I want to send an array for post API in a flutter.
{
"data":[{"question_id":1,"option_id":2},{"question_id":2,"option_id":6}]
}
I want to send the data like the above.
This is my code:
class Sent {
List<Data> data;
Sent({this.data});
Sent.fromJson(Map<String, dynamic> json) {
if (json['data'] != null) {
data = new List<Data>();
json['data'].forEach((v) {
data.add(new Data.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
if (this.data != null) {
data['data'] = this.data.map((v) => v.toJson()).toList();
}
return data;
}
}
class Data {
int questionId;
int optionId;
Data({this.questionId, this.optionId});
Data.fromJson(Map<String, dynamic> json) {
questionId = json['question_id'];
optionId = json['option_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['question_id'] = this.questionId;
data['option_id'] = this.optionId;
return data;
}
}
Here is how I sent it to POST API
Future<Sent> saveAnswer() async {
var data = {"question_id": sent[0][0], "option_id": sent[0][1]};
var url = await Network().link("/exercise/1/saveAnswer");
SharedPreferences localStorage = await SharedPreferences.getInstance();
final token = jsonDecode(localStorage.getString('token'));
http.Response response =
await http.post(Uri.parse(url), body: jsonEncode(data), headers: {
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': 'Bearer $token'
});
if (response.statusCode == 200) {
print(response.body);
} else {
print(response.body);
}
}
While this is how I get the question_id and option_id from CustomCheckBoxGroup.
List<dynamic> sent;
CustomCheckBoxGroup(
buttonValuesList: [
[
snapshot.data.result[index].id,
snapshot.data.result[index]
.options[0].id
],
[
snapshot.data.result[index].id,
snapshot.data.result[index]
.options[1].id
],
[
snapshot.data.result[index].id,
snapshot.data.result[index]
.options[2].id
],
[
snapshot.data.result[index].id,
snapshot.data.result[index]
.options[3].id
],
],
checkBoxButtonValues: (values) {
sent = values;
print(values);
print(sent[0][0]);
print(sent[0][1]);
},
)
Please help me. How to sent an array like I want to post request API.
what is wrong with my code.

I suggest using json.encode
List<dynamic> ListData =
[{"question_id":1,"option_id":2},
{"question_id":2,"option_id":6}];
var json = {
'listKey': json.encode(ListData)
}

Simplest way is to encode the list and add it to json.
For example:
List<dynamic> ListData = [{"question_id":1,"option_id":2},{"question_id":2,"option_id":6}];
var json = {
'listKey': json.encode(ListData)
}

Related

Firestore Map Flutter

Hi Everyone am stuck with this problem am trying to write data this way
Current type
but I always get this
what i get
am using flutter and this is my code
_fetch() async {
final user = await FirebaseAuth.instance.currentUser;
var map = new Map<String, dynamic>();
List<String> productName = [];
map['productName'] = productName;
Stream<QuerySnapshot> productRef = FirebaseFirestore.instance
.collection("cart")
.where('userId', isEqualTo: user?.uid)
.snapshots();
productRef.forEach((field) {
field.docs.asMap().forEach((index, data) {
productName.add(field.docs[index]["name"]);
print(productName);
});
});
getData() async {
return await FirebaseFirestore.instance
.collection('cart')
.where('userId', isEqualTo: user?.uid)
.get();
}
getData().then((QuerySnapshot querySnapshot) {
querySnapshot.docs.forEach((doc) {
var names = doc["name"];
var prices = doc["price"];
FirebaseFirestore.instance.collection('ordersNami').doc().set({
"userId": FirebaseAuth.instance.currentUser?.uid,
"orders": [
{"productName": names, "productPrice": prices},
],
}, SetOptions(merge: true));
});
});
}
i'll explain how it works i have a cart collection and documents field are unique i need to put all the cart products in the structure in first picture

How to handle Special json POST with Flutter

I have a JSON POST that I'm sending from my Flutter app as soon in the below code:
// class connecting value from the textfield to database with json
class LoginProfile {
int id;
String CardNumber;
String ExpiryDate;
String ExpiryYear;
String VerifyCode;
LoginProfile({this.id = 0,this.CardNumber
,this.ExpiryDate,this.ExpiryYear});
factory LoginProfile.fromJson(Map<String, dynamic> map) {
return LoginProfile(
id: map["id"],
CardNumber: map["CardNumber"],ExpiryDate: map["ExpiryDate"],ExpiryYear: map["ExpiryYear"]
);
}
Map<String, dynamic> toJson() {
return {"id": id,"CardNumber": CardNumber
,"ExpiryDate": ExpiryDate,"ExpiryYear": ExpiryYear};
}
#override
String toString() {
return 'Profile{id: $id, "CardNumber": CardNumber
,"ExpiryDate": ExpiryDate,"ExpiryYear": ExpiryYear}';
}
}
Future<bool> createProfile(LoginProfile data) async {
response = await client.post(
"$baseUrl",
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: loginProfileToJson(data),
);
if (response.statusCode == 201) {
return true;
} else {
print(response.body);
}
}
I am meant POST my JSON as below:
{
"Registration": {
"CardNumber":"5105105105105100",
"ExpiryDate":"11",
"ExpiryYear":"2023",
"VerifyCode":"123"
}
}
For some reason, I'm unable to make this work and I need to POST "Registration" as the object like it looks above.
Try with jsonEncode
Future<bool> createProfile(LoginProfile data) async {
response = await client.post(
"$baseUrl",
headers: {'Content-Type': 'application/json; charset=UTF-8'},
body: jsonEncode(loginProfileToJson(data)),
);
if (response.statusCode == 201 || response.statusCode == 200) {
return true;
} else {
print(response.body);
}

Using MultipartFile in flutter to send many images with id foreach item

I am trying to send a list of images using the MultipartFile, the sending is done according to the id and the key of each image ...
the problem, I am told that:
Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'int'
But it's not clear since I don't use any int in my songs ...
Here's my code:
sendPostImages(List responseImages, List userImages) async {
final _path = "files/send";
final uri = Uri.https("$myImgPath", _path);
final imageUploadRequest = http.MultipartRequest('POST', uri);
List imgs = [];
var filePostImg;
for (final item in responseImages) {
imgs.add({
...responseImages[item],
"name": "f$item",
});
filePostImg =
await http.MultipartFile.fromPath("f$item", userImages[item].path);
final listPostImgs =
await http.MultipartFile.fromPath("files", imgs.toString());
imageUploadRequest.files.add(filePostImg);
imageUploadRequest.files.add(listPostImgs);
try {
final streamedResponse = await imageUploadRequest.send();
final response = await http.Response.fromStream(streamedResponse);
if (response.statusCode != 200) {
final Map<String, dynamic> responseData = jsonDecode(response.body);
print('''
erreur de l'envoi des images...
$responseData
''');
}
final Map<String, dynamic> responseData = jsonDecode(response.body);
print(
'''
$responseData
''',
);
} catch (e) {
print(e);
}
}
}
The API Doc:
// When sending several files
"files": ["Object[]", [
// For each file
{
"fid": "String",
"fkey": "String",
"name": "String" // Custom name that you choose
}
]],
// For each file
"f01": "File" // The field's name must be the same as in the "files" object
},

How to pass a List<dynamic> to a List<MyModel> from a JSON?

I have an app that retrieve data from an API, I receive the data as a List and when I print it I can see the data ok.
[
{
"1": "MaxMilyin",
"2": "409733",
"3": "1130794"
},
{
"1": "HippopotamusRex",
"2": "346742",
"3": "1204932"
},
...
]
When I try to pass the list to a list of my model I only get:
[Instance of 'TopTenUsersModel', Instance of 'TopTenUsersModel', ...]
This is my model class, I used this site to generate the class:
class TopTenUsersModel {
String s1;
String s2;
String s3;
TopTenUsersModel({this.s1, this.s2, this.s3});
TopTenUsersModel.fromJson(Map<String, dynamic> json) {
s1 = json['1'];
s2 = json['2'];
s3 = json['3'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['1'] = this.s1;
data['2'] = this.s2;
data['3'] = this.s3;
return data;
}
}
This is the method that I return the data as my model.
static Future<List<TopTenUsersModel>> getTopTenUsers() async{
try{
print("INICIANDO CONEXÃO COM A API...");
var response = await client.get(
Constants.BASE_URL + Constants.getTopTenUsers + Constants.AUTH
);
//print("PRINT RESPONSE NETWORK UTIL: ${response.body}");
// Here I can see the data ok!
List<dynamic> list = json.decode(response.body) as List;
// Here I get 'Instance of 'TopTenUsersModel''
return (json.decode(response.body) as List)
.map((item) => TopTenUsersModel.fromJson(item))
.toList();
} on SocketException catch (e){
throw (e.message);
} finally {
client.close();
}
}
You should be implement below ways
Model class
class TopTenUsersModelResponse {
final List<TopTenUsersModel> list;
TopTenUsersModelResponse({
this.list,
});
factory TopTenUsersModelResponse.fromJson(List<dynamic> parsedJson) {
List<TopTenUsersModel> list = new List<TopTenUsersModel>();
list = parsedJson.map((i) => TopTenUsersModel.fromJson(i)).toList();
return new TopTenUsersModelResponse(list: list);
}
}
replace
List<dynamic> list = json.decode(response.body) as List;
// Here I get 'Instance of 'TopTenUsersModel''
return (json.decode(response.body) as List)
.map((item) => TopTenUsersModel.fromJson(item))
.toList();
by
final List parsed = json.decode(response.body);
List<TopTenUsersModel> responseModelList = new TopTenUsersModelResponse.fromJson(parsed).list;

Processing http post array, display undefined

I have the big problem. I want to display this json, but returning undefined value.
{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }
I use this code in service.ts
public getHomeboxPById(id: string): Observable<HomeboxP> {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let urlSearchParams = new URLSearchParams();
urlSearchParams.append('home_id', id);
urlSearchParams.append('token', this.auth.getCurrentUser().token);
let body = urlSearchParams.toString();
return this.http.post(Api.getUrl(Api.URLS.getHomeboxPById), body, {
headers: headers
})
.map((response: Response) => {
let res = response.json();
if (res.StatusCode === 0) {
return new HomeboxP(res.StatusDescription[0]);
} else if (res.StatusCode === 1) {
this.auth.logout();
} else {
return new HomeboxP(null);
}
});
}
In ts code I call this method getHomeboxPById, like this
editHomeboxPForm: FormGroup;
homeboxp: HomeboxP;
this.editHomeboxPForm = this.fb.group({
'homebox_id': new FormControl('', Validators.required)
});
}
populateFormHomeboxP() {
this.activatedRoute.params.subscribe(
params => {
this.ws.getHomeboxPById(params['id']).subscribe(
homeboxp => {
console.log(homeboxp); // display undefined
this.homeboxp = homeboxp;
this.editHomeboxPForm.controls['homebox_id'].setValue(homeboxp.homebox_id);
}
);
}
);
}
Please, can you help me, why doesn't work?
{"StatusCode":0,"StatusMessage":"OK","StatusDescription":{ "datas": [
{"sensor_serial":"SensorSerial1", "id":"11E807676E3F30B5"},
{"sensor_serial":"sensorserial2", "id":"11E807679D82841L"},
{"sensor_serial":"sensorserial3", "id":"11E80767A5CD2820"} ]
,"home_id":"11E80768K", "active":0, "homebox_id":"11E8076792BD0164J",
"date_created":"2018-02-01T15:55:54.000Z", "date_modified":null,
"serial_number":"serialn1", "user_id":"3"} }
If this is the response of
this.http.post(Api.getUrl(Api.URLS.getHomeboxPById)
Then issue is res.StatusDescription[0] , it should be res.StatusDescription like :
new HomeboxP(res.StatusDescription);

Resources