Xlain 8
Xlain 8

Reputation: 21

how to correctly receive a response from the server in flutter(dart)?

I can't process the response from the server correctly in flutter. The user is created successfully in the database. In the postman application, I also get a response from the server: {"success":true}. But for some reason a connection error is displayed in the console, although the user is also successfully created from the flutter in the table:

Future<void> _sendLanguages(List<String> selectedLanguages, String firstName, String lastName, String email, String password) async {
    final url = Uri.parse('http://localhost/create_user.php');
    final response = await http.post(
      url,
      headers: {"Content-Type": "application/json"},
      body: jsonEncode({
        'first_name': widget.firstName,
        'last_name': widget.lastName,
        'email': widget.email,
        'password': widget.password,
        'languages': _selectedLanguages.map((language) => language.code).toList(),
      }),
    );
    final jsonResponse = json.decode(response.body);
    if (jsonResponse["success"]) {
      Navigator.pop(context);
    }
  } 

I tried changing it to success == true , but that also doesn't work. Dart doesn't properly process the response from the server

Upvotes: 1

Views: 819

Answers (1)

Amirali Eric Janani
Amirali Eric Janani

Reputation: 1750

I think the error you have(and please share the error log), is not related to the response. but you can check the status code and see its behavior:

Future _sendLanguages(List selectedLanguages, String firstName, String lastName, String email, String password) async { 
final url = Uri.parse('http://localhost/create_user.php'); 
final response = await http.post(
  url,
  headers: {"Content-Type": "application/json"},
  body: jsonEncode({
    'first_name': widget.firstName,
    'last_name': widget.lastName,
    'email': widget.email,
    'password': widget.password,
    'languages': _selectedLanguages.map((language) => language.code).toList(),
  }),
);


print('response: ${response.body}'); // this line shows you the response

if (response.statusCode == 200) {
  final jsonResponse = json.decode(response.body);
  if (jsonResponse["success"] == true) {
    Navigator.pop(context);
  }
} else {
  print('Request failed with this status code: ${response.statusCode}.');
 }
}

if the response code wasn't 200, you have problem with your request(if you had checked the url and headers and your body that are correct).

and if the response code is 200 and you have problem again, pay attention to this print('response: ${response.body}'); and see if you are parsing in a correct way or not. and if you still had problem you should say more details to help you.

happy coding.

Upvotes: 1

Related Questions