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;
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With