0

I am using an API for my request. I am taking the response from API as JSON but I can't decode JSON to Map because of this error

_CastError (type 'String' is not a subtype of type 'Map<String, dynamic>' in type cast)

. Here is my API service

Future<LoginResponseModel> login(LoginRequestModel requestModel) async {
String url = "myapi";
var headerss = {HttpHeaders.contentTypeHeader: 'application/json'};
final response =
     await http.post(Uri.parse(url),
     body: jsonEncode(requestModel.toJson()),
     headers: headerss
     );
if (response.statusCode == 200 || response.statusCode == 400) {
  final Map<String, dynamic> test = jsonDecode(response.body) as Map<String, dynamic>;
  return LoginResponseModel.fromJson(test);  
  }  
else {
  print(response.body);
  throw Exception();
     } 
}

Here is my Response Model

class LoginResponseModel {
  late final String token;
  late final String error;

  LoginResponseModel({
    required this.token,
    required this.error,
  });

 factory LoginResponseModel.fromJson(Map<String, dynamic> json) {
   return LoginResponseModel(
     token: json["token"] != null ? json["token"] : "",
     error: json["error"] != null ? json["error"] : "");
 }
}

What I've tried is :

-decoding inside the return

-decoding without giving type Map<String,dynamic>

-decoding with jsonEncode and json.encode

Any help would be awesome.

  • Check [this](https://stackoverflow.com/questions/52774561/flutter-remove-escape-sequence-in-dart) thread, you need to encode it 2 times. – alperenasln May 20 '22 at 11:10
  • Check this [thread](https://stackoverflow.com/questions/52774561/flutter-remove-escape-sequence-in-dart), you need to encode it 2 times. – alperenasln May 20 '22 at 11:11

1 Answers1

1

Try this...

LoginResponseModel loginResponseModel=LoginResponseModel.fromJson(jsonDecode(response.body));