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

Flutter开发宝可梦APP时出现The getter 'pokemon' was called on null报错求助

The getter 'pokemon' was called on null.
Receiver: null
Tried calling: pokemon

报错页面截图

错误原因
  • 异步请求逻辑错误:PokemonlariGetir 方法中混用await与.then语法,导致response实际接收到的是.then的返回值(null),读取response.body失败,pokedex实例未被正确赋值,始终为null。
  • 空安全校验缺失:FutureBuilder 中判定请求完成后,未校验gelenPokedex.data是否为null,直接访问.pokemon属性触发空调用报错。
  • 列表参数缺失:GridView.builder未指定itemCount属性,会出现列表越界访问问题。
解决方案
  1. 清理异步请求方法逻辑,删掉.then嵌套,按顺序执行请求、解析操作
  2. 给FutureBuilder补充数据非空校验,确认数据正常返回后再渲染列表
  3. 给GridView.builder添加itemCount参数,值为宝可梦列表的长度
修正后的核心代码

1. 修正请求方法

Future<Pokedex> PokemonlariGetir() async {
  final response = await http.get(Uri.parse(url));
  final decodedJson = json.decode(response.body);
  pokedex = Pokedex.fromJson(decodedJson);
  debugPrint(pokedex.toString());
  return pokedex;
}

2. 修正FutureBuilder构建逻辑

body: FutureBuilder(
  future: PokemonlariGetir(),
  builder: (context, AsyncSnapshot<Pokedex> gelenPokedex) {
    if (gelenPokedex.connectionState == ConnectionState.waiting) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    } else if (gelenPokedex.connectionState == ConnectionState.done) {
      if (gelenPokedex.hasData && gelenPokedex.data!.pokemon.isNotEmpty) {
        return GridView.builder(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2
          ),
          itemCount: gelenPokedex.data!.pokemon.length,
          itemBuilder: (context, index) {
            return Text(gelenPokedex.data!.pokemon[index].name);
          }
        );
      } else {
        return const Center(child: Text('未获取到有效数据'));
      }
    } else {
      return Center(child: Text('请求失败:${gelenPokedex.error ?? '未知错误'}'));
    }
  }
),

可选优化(空安全适配)

如果项目开启了空安全,建议给模型类的可空属性添加?标识,非必填字段设置默认值,避免编译阶段的空安全报错。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 08:24:03