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

Flutter自定义ReusableCard组件不显示子元素该如何解决?

问题原因
  • 你自定义的ReusableCard组件中,仅声明了cardChild参数用来接收外部传入的子组件,却没有在返回的Container组件上绑定child属性为cardChild,容器没有拿到要渲染的子内容,自然不会展示任何传入的元素。
修复代码

修改ReusableCard的build方法,给Container添加child配置即可,修改后代码如下:

class ReusableCard extends StatelessWidget {
  ReusableCard({
    required this.color,
    this.cardChild,
  });

  final Color color;
  final Widget? cardChild;

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(15),
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(10),
      ),
      // 新增此行,绑定要渲染的子组件
      child: cardChild,
    );
  }
}

如果需要对cardChild为空的情况做兼容兜底,可以写成child: cardChild ?? const SizedBox.shrink(),避免空值带来的潜在警告。
修改完成后重新运行项目,就能正常看到传入的图标和文本内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 00:18:04