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

如何在Flutter中实现带BoxDecoration装饰的编号样式

Flutter 基于BoxDecoration实现带编号卡片UI

实现这类带左侧装饰条、右上角悬浮编号的卡片效果,不需要引入第三方组件,直接用Container的BoxDecoration配合Stack布局就能完成,核心实现逻辑如下:

实现要点

  • 卡片主体:通过BoxDecoration配置圆角、背景色、可选阴影,同时利用左侧边框实现侧边彩色装饰条,不需要额外嵌套冗余组件
  • 编号角标:用Stack+Positioned将角标定位在卡片右上角,通过负偏移做出悬浮突出效果,角标本身用BoxDecoration实现圆形纯色背景,内部居中放置编号文本
  • 内容区:预留足够的内边距,避免内容和侧边装饰条、角标位置重叠

完整可复用代码示例

import 'package:flutter/material.dart';

class NumberedCard extends StatelessWidget {
  final int number;
  final Widget content;
  final Color accentColor;
  final double cardRadius;

  const NumberedCard({
    super.key,
    required this.number,
    required this.content,
    this.accentColor = Colors.blue,
    this.cardRadius = 12,
  });

  @override
  Widget build(BuildContext context) {
    return Stack(
      clipBehavior: Clip.none, // 允许角标超出卡片边界显示
      children: [
        // 卡片主体
        Container(
          width: double.infinity,
          padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(cardRadius),
            // 左侧彩色装饰条直接通过左边框实现
            border: Border(
              left: BorderSide(
                color: accentColor,
                width: 5,
              ),
            ),
            // 可选配置卡片阴影
            boxShadow: [
              BoxShadow(
                color: Colors.grey.withOpacity(0.15),
                blurRadius: 8,
                offset: const Offset(0, 2),
              )
            ],
          ),
          child: content,
        ),
        // 右上角编号角标
        Positioned(
          top: -10,
          right: -10,
          child: Container(
            width: 32,
            height: 32,
            alignment: Alignment.center,
            decoration: BoxDecoration(
              color: accentColor,
              shape: BoxShape.circle,
              // 可选给角标加白边,和卡片边界区分更明显
              border: Border.all(color: Colors.white, width: 2),
            ),
            child: Text(
              number.toString(),
              style: const TextStyle(
                color: Colors.white,
                fontSize: 14,
                fontWeight: FontWeight.bold,
              ),
            ),
          ),
        )
      ],
    );
  }
}

// 调用示例
// NumberedCard(
//   number: 1,
//   accentColor: Colors.orange,
//   content: Text("这是第一个编号卡片的测试内容,你可以替换成任意业务组件比如文本、输入框、列表项等"),
// )

自定义调整说明

  • 要修改装饰条粗细、颜色,直接调整BorderSide的width和color参数即可
  • 要修改角标大小、位置,调整Positioned的偏移值和角标Container的宽高属性
  • 如果需要装饰条为渐变效果,把border属性替换成gradient,配合borderRadius和局部裁切即可实现
  • 卡片内容区支持传入任意自定义组件,不局限于文本

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 04:01:18