Hasani
Hasani

Reputation: 3919

Why I can't check if `response.body` is null or not?

I am trying to see if a username already exist in the database or not, using the following code:

  Future<bool> checkUsername(userName) async {
    try {
      final response = await http.post(
        Uri.parse('http://10.0.2.2:3000/username'),
        headers: {'Content-Type': 'application/json'},
        body: json.encode({'user_name': userName}),
      );

      print('response ${response.body}'); // this prints out "response null"

      if (response.body.isEmpty || response.body == null) {
        print('eee here0');
        return false;
      } else if (json.decode(response.body)['user_id'] == userId) {
        print('eee here1');
        return false;
      } else {
        print('eee here2');
        return true;
      }
    } catch (e) {
      print('some error happenede checking username  $e');
      throw (e);
    }
  }

But it seems the conditions doesn't work and the following exception arises:

Exception has occurred.
NoSuchMethodError (NoSuchMethodError: The method '[]' was called on null.
Receiver: null
Tried calling: []("user_id"))

Even when the result for print('response ${response.body}'); is response null it seems the if statement can't catch it before throwing the exception!

Upvotes: 0

Views: 1254

Answers (4)

jamesdlin
jamesdlin

Reputation: 90155

You're misunderstanding your problem. response.body is not the value null but instead is the String "null". This is evident because if response.body were null, then response.body.isEmpty would have thrown a null pointer exception. (Response.body is non-nullable anyway.)

What you should do is:

      if (response.body.isEmpty) {
        print('eee here0');
        return false;
      }

      var responseJson = json.decode(response.body);
      if (responseJson == null) {
        return false;
      } else if (responseJson['user_id'] == userId) {
        print('eee here1');
        return false;
      } else {
        ...
      }

Upvotes: 0

rblcb
rblcb

Reputation: 1

The issue is related to the order of conditions in your if statement. In Dart, null is considered an empty value. Therefore, response.body.isEmpty will throw a NoSuchMethodError if response.body is null.

You should check if response.body is null before calling any method on it. Your revised condition should look like this:

  if (response.body == null || response.body.isEmpty) {
     print('eee here0');
     return false;
  }

After modifying this, your code should correctly handle cases where response.body is null. If the response.body is null or empty, it will print "eee here0" and return false.

Also, just to ensure, add a null check before decoding the JSON:

  } else if (response.body != null && json.decode(response.body)['user_id'] == userId) {
     print('eee here1');
     return false;

}

This change ensures that the code doesn't attempt to decode null values.

Upvotes: 0

Hasani
Hasani

Reputation: 3919

I modified the code like following and now it works as expected:

  var decodedResponse = json.decode(response.body);

  if ( decodedResponse == null) {
    print('eee here0');
    return false;
  } else if (decodedResponse['user_id'] == userId) {
    print('eee here1');
    return false;
  } else {
    print('eee here2');
    return true;
  }
} catch (e) {
  print('some error happenede checking username  $e');
  throw (e);
}
  

Upvotes: 0

Franklin Diaz
Franklin Diaz

Reputation: 725

use the null-aware operator

  } else if (json.decode(response.body)?['user_id'] == userId) {

Upvotes: -1

Related Questions