flavio_vieira_stack
flavio_vieira_stack

Reputation: 316

flutter error 403 in post request using dio

i have a problem with hate. I'm trying to login using dio, the login method works perfectly, but when I put invalid credentials dio gives me this error:

DioError

Error in execution

I created a boolean function that would return true or false if the statuscode was 200 it would return true and if not it would return false, but when logging in with the right credentials everything is ok, everything happens as it should, but when logging in with invalid credentials this error above causes it. I'm using shared preferences to store the tolken in the app, and the logic would be simple, if it was 200 I would log into the app, otherwise it would show me a snackbar I made in another file, this is my code:

loginFinal() async {
    if (formKey.currentState!.validate()) {
      bool loginIsOk = await loginConect();
      if (loginIsOk) {
        Get.offAllNamed("/home");
        await Future.delayed(const Duration(seconds: 1));
        message(MessageModel.info(
          title: "Sucesso",
          message: "Seja bem vindo(a) influenciador(a)",
        ));
      } else {
        loaderRx(false); //LOADER
        message(MessageModel.error(
          title: "Erro",
          message: "Erro ao realizar login",
        ));
      }
    }
  }

  //LOGICA DE ENTRAR NO APP

  Future<bool> loginConect() async {
    final dio = Dio();
    String baseUrl = "https://soller-api-staging.herokuapp.com";

    loaderRx(true); //LOADER

    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();

    final response = await dio.post(
      baseUrl + "/auth",
      data: jsonEncode(
        {
          "login": emailController.text,
          "senha": passWordController.text,
        },
      ),
      options: Options(
        headers: {'Content-Type': 'application/json; charset=UTF-8'},
        method: "post",
      ),
    );
    if (response.statusCode == 200) {
      await sharedPreferences.setString(
        "token",
        "string: ${response.data["string"]}",
      );
      print("Resposta: ${response.data["string"]}");

      loaderRx(false);

      return true;
    } else {
      print("RESPOSTA: ${response.data}");

      return false;
    }
    
  }
}

Upvotes: 0

Views: 4725

Answers (1)

Muhammad Ali Raza
Muhammad Ali Raza

Reputation: 459

Dio always throw an exception if the status code in the header is not 200, you will need to catch the exception using try catch.

In the catch method, you can check if the type of the error is DioError and then handle that exception,

Here is a code snippet of a login process that I use in my code to handle this behavior.

Future<SignInApiResponse> signInUser(String _email,String _password) async {
try {
  final dio = Dio(ApiConstants.headers());
  final Response response = await dio.post(
    ApiConstants.baseUrl + ApiConstants.signInUrl,
    data: {"email": _email,
"password": _password,
    },
      );
      if (response.statusCode == 200) {
        return SignInApiResponse.fromJson(response.data);
      } else {
        return SignInApiResponse(message: response.toString());
      }
    } catch (e) {
      if (e is DioError) {
        if (e.response?.data == null) {
          return SignInApiResponse(message: Messages.loginFailed);
        }
        return SignInApiResponse.fromJson(e.response?.data);
      } else {
        return SignInApiResponse(message: e.toString());
      }
    }
  }

hopefully, this will help if not you can always use http package that does not throw an exception in similer case

Upvotes: 2

Related Questions