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

Flutter复用OwnCard组件时如何每次设置不同图片而无需复制整段代码

解决方案

通过给OwnCard组件新增动态入参,将可变内容抽离为参数调用时传入即可,改造后的组件代码如下:

class OwnCard extends StatelessWidget {
  // 新增可配置参数,可根据实际需求扩展更多参数(比如文本样式、卡片颜色等)
  final String imageAssetPath;
  final String title;
  final String secondaryText;

  const OwnCard({
    Key? key,
    // 标记为必传参数,也可根据业务需求设置默认值
    required this.imageAssetPath,
    required this.title,
    required this.secondaryText,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Card(
      child: Column(
        children: [
          AspectRatio(
            aspectRatio: 18 / 11,
            // 替换硬编码的图片路径为参数变量
            child: Image.asset(imageAssetPath),
          ),
          Padding(
            padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
            child: Column(
              children: [
                // 替换硬编码的标题为参数变量
                Text(title),
                const SizedBox(
                  height: 12,
                ),
                // 替换硬编码的辅助文本为参数变量
                Text(secondaryText)
              ],
            ),
          )
        ],
      ),
    );
  }
}
调用示例

你只需要在需要使用卡片的位置传入不同的参数即可生成不同样式的卡片,无需重复编写组件代码:

// 生成钻石卡片
OwnCard(
  imageAssetPath: 'assets/diamond.png',
  title: '钻石卡片',
  secondaryText: '钻石等级专属权益',
)

// 生成黄金卡片
OwnCard(
  imageAssetPath: 'assets/gold.png',
  title: '黄金卡片',
  secondaryText: '黄金等级专属权益',
)

如果部分参数不需要每次都传,也可以在构造函数中给参数设置默认值,示例如下:

const OwnCard({
  Key? key,
  required this.imageAssetPath,
  this.title = '默认标题',
  this.secondaryText = '默认辅助说明',
}) : super(key: key);

调用时如果不传title和secondaryText,就会自动使用默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:06:04