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

Flutter:if语句需包裹代码块报错,如何实现值>0才显示且无空分隔线?

问题解决方法

1. 修复if语句报错

报错“Statements in an if should be enclosed in a block”是因为Dart的lint规则要求if后的代码块必须用大括号包裹,避免逻辑歧义。只需给if块添加{}即可解决。

2. 解决CupertinoListSection空分隔线问题

返回普通SizedBox()会让组件占用父组件宽度(高度为0),CupertinoListSection仍会为其生成分隔线。可以通过以下两种方式解决:

方案一:使用SizedBox.shrink()

SizedBox.shrink()是宽高均为0的空组件,不会占用任何空间,CupertinoListSection不会为其生成分隔线。

修正后的完整代码:

FutureBuilder(
  future: item.assetCountAsync,
  builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const SizedBox.shrink();
    }
    if (snapshot.data != null && snapshot.data! > 0) {
      return CupertinoListTile.notched(
        onTap: () {
          Navigator.pop(context, item);
        },
        title: Text(item.name),
        additionalInfo: Text(snapshot.data.toString()),
      );
    } else {
      return const SizedBox.shrink();
    }
  },
)

方案二:使用Visibility组件

通过Visibility控制组件显示状态,同时设置maintainSize: false,确保不显示时不占用空间,避免生成空分隔线。

代码示例:

FutureBuilder(
  future: item.assetCountAsync,
  builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const SizedBox.shrink();
    }
    final shouldShow = snapshot.data != null && snapshot.data! > 0;
    return Visibility(
      visible: shouldShow,
      maintainSize: false,
      maintainAnimation: false,
      maintainState: false,
      child: CupertinoListTile.notched(
        onTap: () {
          Navigator.pop(context, item);
        },
        title: Text(item.name),
        additionalInfo: Text(snapshot.data.toString()),
      ),
    );
  },
)

注意:原代码存在潜在问题——当snapshot.data为null或<=0时,builder函数无返回值,会触发运行时错误,上述方案已补上else分支,确保所有代码路径都返回Widget。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 13:13:23