Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

If statement not throwing true even though the condition is right

I have this block of dart code here.


    var response = await http.post(url);
    var data = response.body;

    await Future.delayed(
      const Duration(seconds: 1),
    );
    if (!mounted) return;


    print("This is data $data");

    if (data == "success") {
      print("if");
    } else if (data == "lacking") {
      print("else if");
    } else {
      print("else");
    }

Here is the php

echo json_encode("success");

Yes it is just this 1 line of code.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

for some reason the output would be "else" instead of my expected "if"

Here’s an image of the output.
enter image description here

I tried putting other words instead of success but it resulted in the same problem. Which is it goes to the else statement.

I found the answer

data is literally equals to "success" with double quotation on them.
To fix it I had to do this.

String success = "\"success\"";

enter image description here

>Solution :

If you look carefully at the output of your print statement you’ll see that data is "success" which you are trying to compare with success, which are not the same string.

This code:

  final data = '"success"'; // try changing this to 'success' for comparison
  print('This is data $data');
  if (data == 'success') {

gives the expected result.

The reason why your response.body is including the double quotes is because it is encoded (by the PHP) as json, but you aren’t decoding it as the Dart end.

Either don’t json encode this simple response, or change your Dart to:

  final data = json.decode(response.body);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading