Search code examples
flutterapidartdeserialization

Unexpected [instance of 'model class'] error in flutter while working with TMDB Api


this is my model class

class TrendingModel {
  int? id;
  String? title;
  String? originalTitle;
  String? overview;
  String? posterPath;
  String? bannerPath;
  String? releaseDate;

  TrendingModel({
    this.id,
    this.title,
    this.originalTitle,
    this.overview,
    this.posterPath,
    this.bannerPath,
    this.releaseDate,
  });

  factory TrendingModel.fromJson(Map<String, dynamic> json) {
    return TrendingModel(
      bannerPath: json["backdrop_path"],
      id: json["id"],
      title: json["title"] ?? json["name"],
      originalTitle: json["original_title"],
      overview: json["overview"],
      posterPath: json["poster_path"],
      releaseDate: json["release_date"],
    );
  }
}

This is my HTTP call and deserialization. I need data inside the ["results"] list coming from TMDB API

my data is in this form
{"something" : value,
"result":[{"key": value,"key":"value"}]
}

class RemoteServices {
  Future<List<TrendingModel>?> getTrending() async {
    String uri =
        "https://api.themoviedb.org/3/trending/all/day?api_key=(My api key)";
    var res =
        await http.get(Uri.parse(uri), headers: {"Accept": "application/json"});
    if (res.statusCode == 200) {
      var data = json.decode(res.body);
      var rest = data["results"] as List;
      var movie = rest.map((e) => TrendingModel.fromJson(e)).toList();
      print(movie);
      return movie;
    } else {
      throw Exception('faild to fetch');
    }
  }
}

when I print my response it shows this in the console

[Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel', Instance of 'TrendingModel']

Solution

  • You can write to access something like : movie[0].title as TrendingModel is main class for parsing. And you have array of movie. so if you want to access then movie[index].key