-1

I'm trying to implement login with the Dio package in my app. When I send the correct email and password I get a 200 status code and user data. But when I send the email or password incorrect backend sends 400 error code and data like this {"message": "User Not Exist","data": [],"status": false} the problem is I'm unable to get the data when I have 400 error because in dio catchError method I can get just error and stacktrace.

Future login(String username, String password) async {
    try {
      String url = "$baseUrl/admin/user/login";
      print(url);
      var res = await dio.post(
        url,
        data: {"email": username, "password": password},
      );
      if (res.statusCode == 400) {
        print(res.data); <----- This dont print anything.
        return false;
      } else {
        print(res.data);
        return true;
      }
      // await Future.delayed(Duration(seconds: 4));
    } catch (e, s) {<----- here I have just error and stacktrace not the data
      print("stacktrace $s");
      print("error $e");
    }
  }

Mr. ZeroOne
  • 904
  • 6
  • 20

2 Answers2

1

I solved this issue using on DioError catch instead of the catch method.

Future login(String username, String password) async {
    try {
      String url = "$baseUrl/admin/user/login";
      print(url);
      var res = await dio.post(
        url,
        data: {"email": username, "password": password},
      );
      if (res.statusCode == 400) {
        print(res.data); <----- This dont print anything.
        return false;
      } else {
        print(res.data);
        return true;
      }
      // await Future.delayed(Duration(seconds: 4));
    } on DioError catch (e) {
      print(e.response.data);<-----------here I can get the data 
      return e.response.data;
    }
  }
Mr. ZeroOne
  • 904
  • 6
  • 20
-1

Take try..catch out and use this form:

dio.post(...).then((response) {...}).catch(...)

Then you can use response as you wish.

You can read this article