0

I am making a mobile app using Flutter & Dart. I have a put request that updated a database. The request keeps giving a bad request 400. The code is as follow:

  Future<void> updateStudent(int id, Student newStudent) async {
    var res = await http.put(
    Uri.parse('https://10.0.2.2:7030/api/Student/{id}?Id=7'),
    headers: {
      "Accept": "application/json",
      "content-type": "application/json"
    },
    body: json.encode({
      'id': newStudent.id,
      'dep_id': newStudent.depId,
      'name_ar': newStudent.nameAr,
      'name_en': newStudent.nameEn,
      'name_moth': newStudent.nameMoth,
      'birth': newStudent.birth,          
    }));
  }

I tried many suggestions. Also I tried to do the request this way code. But same issue.

The API is working just fine with postman but for some reason it does not with Flutter. I postman I used query params and body with raw json There is something wrong but I am not able to find it. Any idea or suggestions?

Update


I debugged the request and it showing an error on "BodyField" stating the Bad state: Cannot access body fields of a Request without "content-type : application/x-www-form-urlencoded

Even though I am using json.

I also tried to change the content type but it is giving unsupported media type.

in postman I am using put method with this url https://localhost:7030/api/Student/{id}?Id=7

enter image description here

HuA
  • 105
  • 2
  • 8

1 Answers1

0

Change your url and body to this:

var url = Uri.https('https://10.0.2.2:7030', 'api/Student/{id}');
var res = await http.put(
url,
headers: {
  "Accept": "application/json",
  "content-type": "application/json"
},
body: {
  'id': newStudent.id,
  'dep_id': newStudent.depId,
  'name_ar': newStudent.nameAr,
  'name_en': newStudent.nameEn,
  'name_moth': newStudent.nameMoth,
  'birth': newStudent.birth,          
});

you already add id in body, no need to put it in url too.

eamirho3ein
  • 16,619
  • 2
  • 12
  • 23