How to check if getting the api was successful or not

Viewed 28

I am checking the login process and I want to know if the process was successful or not

 login() async{
       var f=formstate.currentState;
        if (f!.validate()) {
           var response=  await crud.postrecuest(linklogin, {
           "email":email.text,
           "password":password.text
        });
  
          Navigator.pushNamed(context, "Home");
       }
  }
2 Answers

you can use try-catch

In order to read more about futures and error handling read this Futures and error handling

Sample code snippet which you can try.

 try {
         var response=  await crud.postrecuest(linklogin, {
         "email":email.text,
         "password":password.text
        });
  
        }
          catch(error) {
             your code here : What code to execute if an error occurs
        }
       //If there is no error, we will reach this line
       Navigator.pushNamed(context, "Home");

You can also check the status code of the response. First, you have to make sure what is the statusCode of the response to successful login (probably 200). Then check if your response has such a status code.

Code:

var response=  await crud.postrecuest(linklogin, {
 "email":email.text,
 "password":password.text
});
if (response.statusCode != 200) {
  throw LoginFailure();
} else {
  Navigator.pushNamed(context, "Home");
}
Related