Search code examples
androidiosfirebaseflutterflutter-layout

Get multiple response from API in flutter


I have a user registration API written in node but the API gives me three types of responses

  1. If the registration is successful then the below JSON is the response
     {
      "message": "success",
      "ccontent": {
        "_id": "5ef7c4c414529241205fb590",
        "email": "[email protected]",
        "password": "$2b$05$4TFPKJ83O7jSPhjtIIDj1ud5pjhS9GY.I0C.IFlBDyUFsd6i4E3Ci",
        "__v": 0
      }
    }
  1. If the user already exists it just gives me a string response

    already-exists

  2. If error occurred

    error-occurred

I have a future function to get the response from the API

class RegistrationService {
  String registrationUrl = 'http://192.168.1.6:8080/api/user/create';

  Future userRegistration(email, password) async {
    Response response = await post(registrationUrl,
        body: {"email": email, "password": password});
    var result = jsonDecode(response.body);
    return RegistrationResponse.fromJson(result);
  }
}

This works only when the user registration is a success but when it fails error occurs telling unhandled exception 'already-exists' or 'error-occurred'

How can I get all types of responses from the API in this future function?

Thanks in advance.


Solution

  • You could throw an exception in case response is already-exists or error-occurred

    class RegistrationService {
      String registrationUrl = 'http://192.168.1.6:8080/api/user/create';
    
      Future<Map<String, dynamic> userRegistration(email, password) async {
        Response response = await post(registrationUrl,
            body: {"email": email, "password": password});
        
        if (userAlreadyExist(response.body)) {
           // already-exists response
            throws UserAlreadyExistException();
        }
        else if (errorOccurred(response.body)) {
            // error occurred response
            throws SomeOtherException();
        }
    
        var result = jsonDecode(response.body);
        return RegistrationResponse.fromJson(result);
      }
    }
    

    You would need to implement methods userAlreadyExist and errorOccurred to detect this situation and decide what's the best exception type for every case. You would also need to cath the exception when you call userRegistration so you can react properly.