Home > other >  If statement not throwing true even though the condition is right
If statement not throwing true even though the condition is right

Time:11-05

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.

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

CodePudding user response:

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);

CodePudding user response:

Using == to compare strings doesn't work. An easy way is (StringA.compareTo(StringB) == 0). Make sure StringA is not null when doing this.

  • Related