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

Flutter中如何实现自定义形状的TabBar指示器

自定义TabBar指示器实现方案

核心思路

通过自定义CustomPainter,使用Path绘制带底部尖角的圆角矩形形状,替代默认TabBar指示器。

代码实现

1. 自定义指示器Painter

import 'package:flutter/material.dart';

class CustomTabIndicator extends CustomPainter {
  final Color color;
  final double radius;
  final double triangleHeight;

  CustomTabIndicator({
    required this.color,
    this.radius = 8.0,
    this.triangleHeight = 6.0,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..color = color;
    final path = Path();

    // 绘制左上角圆角
    path.moveTo(radius, 0);
    // 绘制右上角圆角
    path.arcToPoint(
      Offset(size.width - radius, 0),
      radius: Radius.circular(radius),
    );
    // 连接右下角到尖角上方
    path.lineTo(size.width, size.height - triangleHeight);
    // 绘制底部中间尖角
    path.lineTo(size.width / 2, size.height);
    // 连接左下角到尖角上方
    path.lineTo(0, size.height - triangleHeight);
    // 闭合左上角圆角
    path.arcToPoint(
      Offset(radius, 0),
      radius: Radius.circular(radius),
      clockwise: false,
    );

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return oldDelegate is CustomTabIndicator &&
        (oldDelegate.color != color ||
            oldDelegate.radius != radius ||
            oldDelegate.triangleHeight != triangleHeight);
  }
}

2. 在TabBar中使用

TabBar(
  tabs: const [
    Tab(text: "首页"),
    Tab(text: "分类"),
    Tab(text: "我的"),
  ],
  indicator: CustomPaint(
    painter: CustomTabIndicator(
      color: Colors.blue,
      radius: 8.0,
      triangleHeight: 6.0,
    ),
  ),
  // 可选:指示器宽度跟随tab宽度/文字宽度
  indicatorSize: TabBarIndicatorSize.tab,
)

调整提示

  • 修改radius参数控制圆角大小,triangleHeight控制底部尖角高度
  • 若需要指示器宽度跟随文字,将indicatorSize设为TabBarIndicatorSize.label
  • 如需描边效果,可给Paint添加style: PaintingStyle.stroke和strokeWidth参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 14:27:32