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

Flutter运行报NoSuchMethodError:null对象调用[]方法该如何解决?

错误原因

你调用接口拿到的response.data不是直接的电影列表,TheMovieDB的流行电影接口返回的结构外层是对象,包含page、total_pages、results等字段,真正的电影列表存在response.data['results']里。你现在直接遍历response.data、把错误的内容存到titulos数组里,后续读取['title']的时候自然就拿到null值报错了。


修复步骤

  • 第一步,修改_getNames方法里的遍历逻辑,把接口返回的results字段作为遍历对象:
void _getNames() async {
  final response = await dio.get(
      'https://api.themoviedb.org/3/movie/popular?api_key=0e685fd77fb3d76874a3ac26e0db8a4b&language=en-US&page=1');
  print(response.data);
  List tempList = new List();
  // 遍历response.data里的results数组
  List results = response.data['results'];
  for (int i = 0; i < results.length; i++) {
    tempList.add(results[i]);
  }
  setState(() {
    titulos = tempList;
    filteredNames = titulos;
  });
}
  • 第二步,增加加载状态判断,避免接口还没返回的时候,titulos是空数组就渲染列表,极端情况下也会触发空报错:
    修改_buildList方法,先判断数组是否有数据,没有的时候展示加载提示:
Widget _buildList() {
  // 新增加载判断
  if (titulos.isEmpty) {
    return Center(child: CircularProgressIndicator());
  }
  if (!(_searchText.isEmpty)) {
    List tempList = new List();
    for (int i = 0; i < filteredNames.length; i++) {
      if (filteredNames[i]['title']
          .toLowerCase()
          .contains(_searchText.toLowerCase())) {
        tempList.add(filteredNames[i]);
      }
    }
    filteredNames = tempList;
  }
  return ListView.builder(
    itemCount: filteredNames.length,
    itemBuilder: (BuildContext context, int index) {
      return new ListTile(
        title: Text(filteredNames[index]['title']),
        onTap: () => print(filteredNames[index]['title']),
      );
    },
  );
}
  • 可选优化:可以给取值逻辑加空兼容判断,避免某条电影数据没有title字段时报错,比如把filteredNames[i]['title']改为filteredNames[i]['title'] ?? '无标题'。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 05:54:08