调用IMDB API时遇空指针错误:The method '[]' was called on null
问题分析与解决方案
错误根源
你调用的IMDB get-details接口返回的是单个电影的JSON对象,但你在FutureBuilder里错误使用了ListView.builder(用于渲染数组列表的组件),试图通过索引snapshot.data[index]访问数据——单个对象不存在索引,导致imdb变量为null,最终调用imdb["title"]时触发The method '[]' was called on null错误。
另外你的代码缺少完整的请求状态判断(比如加载中、请求失败的情况),也没有处理接口返回数据为空的场景。
修复步骤
1. 调整FutureBuilder逻辑,适配单个对象数据
直接渲染单个电影详情,不需要用ListView.builder,因为接口返回的不是数组。
2. 完善状态判断
增加加载中、请求错误、数据为空的处理逻辑,避免异常。
修改后的完整代码
数据请求部分(优化类型标注)
Future<Map<String, dynamic>?> getMoviesData() async { var uri = Uri.https( 'imdb8.p.rapidapi.com', '/title/get-details', {"tconst": 'tt0944947'}); var response = await http.get(uri, headers: { 'X-RapidAPI-Key': '4c475a8679mshd659a75041ce1aap115573jsn8903b41a82cf', 'X-RapidAPI-Host': 'imdb8.p.rapidapi.com' }); print(response.statusCode); print(response.body); if (response.statusCode == 200) { return jsonDecode(response.body); } else { // 请求失败时返回null return null; } }
UI渲染部分
return Scaffold( body: FutureBuilder<Map<String, dynamic>?>( future: getMoviesData(), builder: (context, snapshot) { // 加载中状态 if (snapshot.connectionState == ConnectionState.waiting) { return const Center(child: CircularProgressIndicator()); } // 请求错误状态 if (snapshot.hasError) { return Center(child: Text('请求出错: ${snapshot.error}')); } // 无数据状态 if (!snapshot.hasData || snapshot.data == null) { return const Center(child: Text('未获取到数据')); } // 正常渲染数据 var movie = snapshot.data!; return Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ // 用空值运算符避免字段为null的情况 Text(movie["title"] ?? '无标题'), // 可添加其他字段,比如上映年份 if (movie["year"] != null) Text('上映年份: ${movie["year"]}'), ], ), ); }, ), );
额外提醒
- 注意保护你的RapidAPI Key,不要将其暴露在公开代码中,建议使用环境变量或本地配置文件管理。
- 你之前打印的
response.body可以验证返回结构:它是单个对象(比如{"title": "Game of Thrones", "year": 2011, ...}),而非数组,这也是为什么不能用ListView.builder的核心原因。
内容的提问来源于stack exchange,提问作者yuso
相关产品推荐
相关产品推荐

