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

Why I'm getting this error: The argument type 'String' can't be assigned to the parameter type 'int'?

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

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

>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) {
  ...
}

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