This is the response of the statusCode and body if the user enters the wrong email and password. I/flutter (20074): 200 I/flutter (20074): {"code":1,"message":"invalid username or password","data":null} and if user enter a correct email and password this is the response I/flutter (20074): 200 I/flutter (20074): {"code":0,"message":"success","data":{"Id":121106,"Name":"User 1","Email":"user@gmail.com","Token":"2db0ce86-2dc0-4381-97de-ce6e0c341d90"}}. I want to validate my login if the user enters the wrong email and password. It will display "Invalid credentials" and it will not go to another page. My problem is when I this response.body['code'] == 0 to my if statement I got this error The argument type 'String' can't be assigned to the parameter type 'int'. How can I solve this problem?
create function to call login post api
Future<void> login() async {
if(emailController.text.isNotEmpty && passController.text.isNotEmpty) {
var headers = {"Content-type": "application/json"};
var myBody = {
'email' : emailController.text,
'password' : passController.text,
};
var response = await http.post(Uri.parse("url"),
headers: headers,
body: jsonEncode( myBody ));
if(response.statusCode == 200 && response.body['code'] == 0) {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => const SecondRoute()));
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("Invalid Credentials.")));
}
} else {
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(content: Text("Blank Field Not Allowed")));
}
}
>Solution :
The object response.body is a string. To access individual objects within the response, you first need to decode the json.
var response = await http.post(Uri.parse("url"),
headers: headers,
body: jsonEncode( myBody ));
final data = json.decode(response.body);
if (response.statusCode == 200 && data['code'] == 0) {
...
}