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

接入null safety空安全依赖库后代码无法运行,添加空检查仍报错

问题原因

你的报错核心是空安全下AsyncSnapshot的data属性默认可空,即便你通过snapshot.hasData判断了非空,Dart类型系统也无法自动完成可空类型到非空类型的推导,所以直接调用snapshot.data.length会触发空安全编译报错。

修复方案

  • 给FutureBuilder指定明确的泛型类型,和你的allPerson()方法返回的Future泛型保持一致即可,比如allPerson返回的是Future<List<Map>>,就写FutureBuilder<List<Map>>
  • 在确认snapshot.hasData为true的分支里,用!操作符对snapshot.data做强制非空解包,你已经提前做了非空判断,这里解包不会有运行时异常。

修改后完整代码

body: FutureBuilder<List<Map>>(
    future: allPerson(),
    builder: (context, snapshot) {
      if (snapshot.hasError) print(snapshot.error);
      return snapshot.hasData
          ? ListView.builder(
              itemCount: snapshot.data!.length,
              itemBuilder: (context, index) {
                List list = snapshot.data!;
                return Card(
                  child: ListTile(
                    title: Container(
                      width: 100,
                      height: 100,
                      child: Image.network(
                          "http://192.168.1.101/image_upload_php_mysql/uploads/${list[index]['image']}"),
                    ),
                    subtitle: Center(child: Text(list[index]['name'])),
                  ),
                );
              })
          : Center(
              child: CircularProgressIndicator(),
            );
    },
  ),

可选优化

如果你不想使用!强制解包,也可以用类型强转的方式提前把非空值赋值给新变量,写法更易维护:

builder: (context, snapshot) {
  if (snapshot.hasError) print(snapshot.error);
  if (snapshot.hasData) {
    final List list = snapshot.data as List;
    return ListView.builder(
      // 后续直接使用list变量即可
    );
  } else {
    return const Center(child: CircularProgressIndicator());
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 21:15:00