I'm creating a data to an API and these API returns a list that have a nested list and an array. what I wanted to do is combine the array with the nested list and create a new list. my response returns "client" list and "phones" array. I want to create "supplier" list and merge the two data I fetched. the "client" list objects to the "supplier" list as it's object and add "phones" array as an object to "supplier"
the response of the API
{
"client": {
"name": "Glorymawn",
"address": "bole",
"tin_no": 98909876,
"updated_at": "2022-10-11T16:23:00.000000Z",
"created_at": "2022-10-11T16:23:00.000000Z",
"id": 24
},
"phones": [
{
"id": 59,
"client_id": 23,
"phone_number": 90865132314,
"email": "[email protected]",
"model": "Supplier",
"category": "Manager",
"created_at": "2022-10-11T16:23:00.160624Z",
"updated_at": "2022-10-11T16:23:00.160636Z"
}
],
"message": "Client created successfully"
}
what I want to create is
{
"supplier": {
"id": 24,
"name": "Glorymawn",
"address": "bole",
"tin_no": "98909876",
"created_at": "2022-10-11T16:23:00.000000Z",
"updated_at": "2022-10-11T16:23:00.000000Z",
"phones": [
{
"id": 59,
"client_id": 23,
"phone_number": 90865132314,
"email": "[email protected]",
"model": "Supplier",
"category": "Manager",
"created_at": "2022-10-11T16:23:00.160624Z",
"updated_at": "2022-10-11T16:23:00.160636Z"
}
]
}
}
my create call
Future createSupplier(
String name, String address, String tin_no, List<Phones> phones) async {
Uri url = Uri.parse("${BASE_URL}supplier");
SupplierController supplierController = Get.put(SupplierController());
final response = await http
.post(url,
headers: <String, String>{
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer $TOKEN',
},
body: jsonEncode(<String, dynamic>{
'name': name,
'address': address,
'tin_no': int.parse(tin_no),
'phones': phones.toList()
}))
.then((value) {
if (value.statusCode == 200) {
supplierController.setsupplierPress(true);
print(json.decode(value.body)['client']);
supplierController.createSupplier(
Suppliers.fromJson(json.decode(value.body)['client']));
Get.back();
supplierController.setsupplierPress(false);
print('<<<<<<<<<<' value.body);
print(json.decode(value.body)['client']);
print("success");
} else if (value.statusCode == 500) {
Get.snackbar("Data Exists", "The data you provided already exists.");
} else {
Get.snackbar("Failed", "Failed to create client, try again later");
}
});
}
how can I make this happen?
CodePudding user response:
Create a supplier map as follow:
dynamic response= json.decode(value.body);
Map sup =response['client'];
sup['phones'] =response['phones'];
Map supplier['supplier']=sup;
CodePudding user response:
Just head to the json2dart and paste your json there then it will give you the classes you need
After that its simply decoding your response from server the class will do the job you need