Future<LoginResponse> authenticate(LoginRequest request) async {
var url = _baseUrl + loginUrl;
Map<String, String> headers = {'Content-Type': 'application/json;'};
final res = await http.post(url, headers: headers, body: request.toJson());
if (res.statusCode == 201) {
Map<String, dynamic> response = jsonDecode(res.body);
var json = LoginResponse(res.statusCode,
response: response, token: response['user_access_token']['key']);
return json;
} else {
Map<String, dynamic> response = jsonDecode(res.body);
var json =
LoginResponse(res.statusCode, response: response, error: res.body);
return json;
}
}
This is my code in UserRepository and I am using flutter_bloc to pass in the request model.
Below is the logic in the AuthBloc. I am pretty sure the issue is in the http.post
method because when I remove the headers my request is processed but responds with an error.
Stream<AuthState> _mapLoginToState(String email, String password) async* {
yield AuthenticationLoadingState();
LoginRequest request =
LoginRequest(email: email, password: password);
var res = await userRepository.authenticate(request);
if (res.code == 201) {
var token = res.token;
if (token != '' && token != null) {
await userRepository.saveToken(token);
yield AuthenticatedState();
} else {
await userRepository.deleteToken();
yield UnAuthenticatedState();
}
} else {
print(res.error);
}
}