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

Flutter中如何为FutureBuilder内的ListView.builder添加无数据空状态Widget

实现方案

你只需要在 FutureBuilder 的判断分支中新增空列表判断逻辑即可,修改后的完整代码如下:

return FutureBuilder(
  future: findAllDoctor(),
  builder: (BuildContext context, AsyncSnapshot<List<Doctor>> snapshot) {
    // 加载中状态
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const Center(child: CircularProgressIndicator());
    }
    // 加载出错状态
    if (snapshot.hasError) {
      return Center(child: Text('加载异常:${snapshot.error.toString()}'));
    }
    // 拿到返回数据
    if (snapshot.hasData) {
      final doctorList = snapshot.data!;
      // 列表为空时展示暂无数据提示
      if (doctorList.isEmpty) {
        return const Center(child: Text('暂无数据'));
      }
      // 列表有数据时渲染列表项
      return ListView.builder(
        itemCount: doctorList.length,
        itemBuilder: (BuildContext context, int index) {
          final doctor = doctorList[index];
          return Card(
            child: ListTile(
              contentPadding: const EdgeInsets.all(8.0),
              title: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("${doctor.firstName} ${doctor.lastName}"),
                  Text(
                    doctor.phone,
                    style: const TextStyle(
                      fontSize: 14,
                      color: Colors.grey,
                    ),
                  ),
                ],
              ),
              subtitle: Text("${doctor.address} ${doctor.nameOfTheClinic}"),
            ),
          );
        },
      );
    }
    // 异常情况兜底
    return const Center(child: Text('加载失败'));
  },
);

改动说明

  • 拆分了原有加载、数据返回的判断逻辑,新增空列表判断分支,数据库无数据时直接展示「暂无数据」提示
  • 补充了错误状态处理,避免请求异常时页面一直停留在加载状态,可根据业务需求调整错误提示的样式和文案
  • 将重复调用的 snapshot.data! 抽成局部变量 doctorList,简化代码同时减少空断言的重复使用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 00:54:07