'How to send data through patch request in flutter
I am facing issue in sending the below data as a patch request.
The issue I am facing is I am not able to pass the Detail object data within another object(AddPerson) hence if you could please help me resolve this issue.
Additionally the data is being captured correctly but the format of the data as shown in sample data is not being captured.
Hence if you could please help in resolving this issue.
Below is the code
Model.dart
class AddPerson {
String? personId;
String? personName;
List<Details>? details;
AddPerson(
{this.personId, this.personName, this.details});
AddPerson.fromJson(Map<String, dynamic> json) {
personId = json['personId'];
personName = json['personName'];
if (json['details'] != null) {
details = <Details>[];
json['details'].forEach((v) {
details!.add(new Details.fromJson(v));
});
}
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['personId'] = this.personId;
data['personName'] = this.personName;
if (this.details != null) {
data['details'] = this.details!.map((v) => v.toJson()).toList();
}
return data;
}
}
class Details with ChangeNotifier {
String? type;
String? price;
String? notificationId;
Details({this.type, this.price, this.notificationId});
Details.fromJson(Map<String, dynamic> json) {
type = json['type'];
price = json['price'];
notificationId = json['notification_id'];
}
Map<String, dynamic> toJson() {
final Map<String, dynamic> data = new Map<String, dynamic>();
data['type'] = this.type;
data['price'] = this.price;
data['notification_id'] = this.notificationId;
return data;
}
}
Provider.dart
Future<void> updateAddPerson(
List<AddPerson> newNotification, List<Details> s) async {
Map<String, String> headers = {
// "Content-Type": "charset=utf-8",
"Content-type": "application/json"
};
var uri = Uri.parse('http://localhost:3001/users/update/person');
try {
var request = http.MultipartRequest('PATCH', uri);
request.headers.addAll(headers);
for (int i = 0; i <= newNotification.length - 1; i++) {
request.fields['personId[$i]'] = '${newNotification[i].personId}';
request.fields['personName[$i]'] = '${newNotification[i].personName}';
for (int m = 0; m <= s.length - 1; m++) {
request.fields['notification_id[$m]'] = '${s[m].notificationId}';
request.fields['type[$m]'] = '${s[m].type}';
request.fields['price[$m]'] = '${s[m].price}';
}
}
var response = await request.send();
print(response.statusCode);
if (response.statusCode == 201) {
notifyListeners();
} else {
print('invalid data ');
}
} catch (error) {
print('NA');
}
}
Sample result
[
{
"personId": "1",
"personName":"Akash”,
"details": [
{
"notification_id": 1,
"type": “SUV”,
"price": "200"
},
{
"notification_id": 2,
"type": “SUV”,
"price": "250"
}
]
}
]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|