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!