Getting type mismatch error when making HTTP requests to movie API in Flutter

I’m working on a Flutter app that needs to fetch movie information from an external API. I keep running into the same error and can’t figure out what’s wrong. The error message says something about type mismatch with maps. Here’s my API service class:

class ApiService {
  static Future<Map<String, dynamic>> fetchMovieData(String movieId, String apiUrl) async {
    Map<String, dynamic> responseData = {};
    
    final requestHeaders = {
      "Content-Type": "application/json",
      "X-RapidAPI-Key": "YOUR_API_KEY_HERE",
      "X-RapidAPI-Host": "movie-db-api.p.rapidapi.com"
    };
    
    Map<String, String> params = {
      'id': movieId,
      'format': 'json',
      'details': 'extended'
    };
    
    try {
      final requestUri = Uri.https(apiUrl, "/", params);
      final apiResponse = await http.get(requestUri, headers: requestHeaders);
      Map<String, dynamic> parsedResponse = json.decode(apiResponse.body);
      responseData['result'] = parsedResponse;
      return responseData;
    } catch (error) {
      responseData['errorMessage'] = 'Request failed: ' + error.toString();
      return responseData;
    }
  }
}

This is how I’m trying to use it:

Map<String, dynamic> apiResult = {};
String targetMovieId = 'tt98765432';
String baseApiUrl = 'movie-db-api.p.rapidapi.com';
apiResult = await ApiService.fetchMovieData(targetMovieId, baseApiUrl);

The error keeps showing up and I’m not sure what’s causing the type issue. Any ideas what might be wrong?

You’re missing status code validation. The JSON decoder throws type errors when the response isn’t actually JSON - you might be getting HTML error pages back. Also, that Uri.https syntax looks wrong. Try Uri.parse('https://$apiUrl/movie/$movieId') instead of using the params approach.

You’re encountering that type mismatch because the API is likely returning an array instead of an object. Movie APIs frequently send back List when you’re expecting Map<String, dynamic>. I faced a similar issue with a movie API recently. First, do a type check before casting. Use dynamic decodedJson = json.decode(apiResponse.body); and then verify if (decodedJson is Map<String, dynamic>) before attempting to cast it. Additionally, it’s worth checking your endpoint; the path parameter in Uri.https might need to be ‘/movie’ instead of just ‘/’. Refer to your API documentation to ensure the endpoint structure is correct.

I encountered a similar problem when working with movie APIs in Flutter. While your code is mostly correct, I recommend checking if HTTP status codes are handled appropriately. If you receive an error code like 404 or 500, json.decode will fail since the response may not be valid JSON. Additionally, be aware that some APIs might return an array instead of an object for specific endpoints, which could lead to a type mismatch when assigning to Map<String, dynamic>. Try printing apiResponse.body first to verify the content received. It’s also a good practice to check if apiResponse.statusCode equals 200 before proceeding with the decoding to pinpoint the source of the issue.