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

如何正确使用ListView实现仅单次显示无内容提示?

解决方案:让提示仅显示一次

不需要重写全部代码,只需要调整数据过滤和UI渲染逻辑即可解决重复显示提示的问题,核心思路是先过滤出符合条件的产品,再根据过滤结果决定显示内容:

修改后的代码示例

child: FutureBuilder<List<Product>>(
  future: products,
  builder: (context, snapshot) {
    if (!snapshot.hasData) {
      return const Center(
        child: CircularProgressIndicator(),
      );
    }

    final products = snapshot.data!;
    // 提前过滤出符合条件(difference == 0)的产品
    final validProducts = products.where((product) {
      DateTime productExpire = DateTime.parse(product.date);
      final today = DateTime.now();
      final difference = calcDays(today, productExpire);
      return difference == 0;
    }).toList();

    // 根据过滤结果渲染对应UI
    if (validProducts.isNotEmpty) {
      return Padding(
        padding: const EdgeInsets.all(10.0),
        child: ListView.builder(
          itemCount: validProducts.length,
          itemBuilder: (context, index) {
            return cardUI(
              // 传入validProducts[index]的相关数据
              ...
            );
          },
        ),
      );
    } else {
      // 无符合条件产品时,仅显示一次提示
      return const Center(
        child: Text('Nothing to display!'),
      );
    }
  },
),

关键调整说明

  1. 提前过滤数据:通过where方法一次性筛选出所有difference == 0的产品,避免在ListView.builder的每个item中重复判断。
  2. 根据过滤结果分支渲染:
    • 若有符合条件的产品,用ListView渲染这些产品;
    • 若无符合条件的产品,直接返回一次提示文本,不再使用ListView,从根源避免重复显示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 22:36:26