You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用TMDB API按分类ID取影片时遇类型不匹配错误

问题:Flutter调用TMDB /discover/movie接口时出现类型转换错误

在使用Flutter的Bloc/Cubit框架调用TMDB的/discover/movie接口,传入int类型分类ID获取影片数据时,报错:Type int is not subtype of type iterable<dynamic>,但用Postman传相同ID能正常返回数据。

错误原因

问题出在请求参数的传递逻辑上:TMDB的with_genres参数要求传入字符串类型的分类标识(单个ID直接转字符串,多个ID用逗号分隔),但你代码里直接传入了int类型的categoryId。

Dart的Uri.https方法在处理参数值时,若传入int类型,内部会错误地将其当作可迭代对象(如列表)处理,最终触发类型不匹配的异常。

修复方案

将categoryId转换为字符串类型后再传入参数即可解决问题:

修改后的完整代码:

import 'dart:convert';

import 'package:bloc/bloc.dart';
import 'package:http/http.dart' as http;
import 'package:meta/meta.dart';
import 'package:movies/components/config/api_config.dart';
import 'package:movies/views/browse/manger/models/movies_genres_model.dart';

part 'movies_genres_state.dart';

class MoviesGenresCubit extends Cubit<MoviesGenresState> {
MoviesGenresCubit() : super(MoviesGenresInitial());

List<Results> movies = [];

Future<void> fetchMoviesByGenres(int categoryId) async {
 emit(MoviesGenresLoading());
 try {
   Uri url = Uri.https(ApiConfig.BASE_URL, "/3/discover/movie", {
     'with_genres': categoryId.toString(), // 关键修改:将int转为字符串
     'sort_by': 'popularity.desc',
   });
   http.Response response = await http.get(url, headers: {
     "Authorization": ApiConfig.tokenKey,
   });
   Map<String, dynamic> json = jsonDecode(response.body);

   MoviesGenres moviesGenres = MoviesGenres.fromJson(json);

   movies = moviesGenres.results ?? [];

   emit(MoviesGenresSuccess());
 } catch (e) {
   emit(MoviesGenresFailure(e.toString()));
 }
}
}

多分类ID场景补充

如果需要同时筛选多个分类的影片,只需将ID列表用逗号拼接成字符串:

// 示例:同时筛选分类ID为18和36的影片
List<int> targetGenres = [18, 36];
'with_genres': targetGenres.join(','),

内容的提问来源于stack exchange,提问作者Icarus

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 00:19:50