Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send nested Json in body as http post request from Flutter

Tags:

http

flutter

dart

I'm trying to send a nested Json as body in one of the http post request from the flutter app I had been working on.

{
      "user" : {
        "UserName": "username",
        "password":"password",
        "Name": "name",
        "Email": "email"
      }
}

I tried many methods that were available online to do it, but every time I'm getting a 500 error. Below is a class to convert it into Json.

class SignupJson {
  String username;
  String email;
  String name;
  String password;

  SignupJson(this.email, this.name, this.password, this.username);

  Map toJson() =>{"user":{
    'UserName': username,
    'Name': name,
    'password': password,
    'Email': email
  }};

}

And pass on it to this for a post request. (I've put an arbitrary url link)

Future<int> attemptSignup ({String username, String password, String name, String email}) async {



    SignupJson data = SignupJson(username: username, password: password, name: name, email: email);
    var url = 'url';

    String body = jsonEncode(json);

    var res = await http.post(url,
    body: body);
    return res.statusCode;

  }
like image 932
Siddharth Singh Avatar asked Oct 20 '25 03:10

Siddharth Singh


1 Answers

Add header like this:

Map<String, String> headers = {HttpHeaders.contentTypeHeader: "application/json"};

then in post request:

var res = await http.post(url, headers: headers, body: body);
like image 164
Mehrdad Davoudi Avatar answered Oct 21 '25 16:10

Mehrdad Davoudi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!