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

如何实现支持多属性自定义的可复用Flutter CustomCard组件

可复用Flutter CustomCard组件实现方案

实现思路

  • 把所有需要动态配置的属性提取为CustomCard组件的入参
  • 无特殊要求的属性可以设置默认值,降低使用成本
  • 点击事件通过VoidCallback类型参数透出给调用方自定义实现

完整组件代码

import 'package:flutter/material.dart';

class CustomCard extends StatefulWidget {
  // 外层卡片颜色
  final Color outerCardColor;
  // 内嵌卡片颜色
  final Color innerCardColor;
  // 图标颜色
  final Color iconColor;
  // 标题文字颜色
  final Color textColor;
  // 展示的图标
  final IconData icon;
  // 标题文字
  final String title;
  // 点击回调
  final VoidCallback onTap;

  const CustomCard({
    super.key,
    // 对齐原有默认样式设置默认值,常规使用时无需重复传参
    this.outerCardColor = Colors.red,
    this.innerCardColor = Colors.white,
    this.iconColor = Colors.red,
    this.textColor = Colors.white,
    required this.icon,
    required this.title,
    required this.onTap,
  });

  @override
  State<CustomCard> createState() => _CustomCardState();
}

class _CustomCardState extends State<CustomCard> {
  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.fromLTRB(20, 10, 20, 1),
      color: widget.outerCardColor,
      child: InkWell(
        onTap: widget.onTap,
        child: ListTile(
          leading: Card(
            color: widget.innerCardColor,
            margin: const EdgeInsets.all(5),
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Icon(
                widget.icon,
                size: 20,
                color: widget.iconColor,
              ),
            ),
          ),
          title: Text(
              widget.title,
              style: TextStyle(color: widget.textColor, fontSize: 16)
          ),
        ),
      ),
    );
  }
}

使用示例

// 页面中调用示例
Column(
  children: [
    CustomCard(
      icon: KycIcons.add_a_photo,
      title: '上传自拍',
      onTap: () {
        // 自定义点击逻辑:调起相机拍摄自拍
        debugPrint('触发上传自拍逻辑');
      },
    ),
    CustomCard(
      icon: Icons.credit_card,
      title: '上传身份证',
      outerCardColor: Colors.blue,
      iconColor: Colors.blue,
      onTap: () {
        // 自定义点击逻辑:跳转身份证上传页面
        debugPrint('触发上传身份证逻辑');
      },
    ),
    CustomCard(
      icon: Icons.bankcard,
      title: '绑定银行卡',
      outerCardColor: Colors.green,
      iconColor: Colors.green,
      textColor: Colors.black87,
      innerCardColor: Colors.grey.shade200,
      onTap: () {
        // 自定义点击逻辑:跳转银行卡绑定页面
        debugPrint('触发绑定银行卡逻辑');
      },
    )
  ],
)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 05:24:04