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

如何在Flutter中实现特定样式的底部圆角TabBar指示器?

如何在Flutter中实现特定样式的底部圆角TabBar指示器?

我刚好实现过类似的TabBar指示器效果,下面给你一套完整的解决方案,完全匹配你提到的这些需求:

  • 仅在选中标签底部显示圆角矩形指示器,仅左上角和右上角圆角,底部平直
  • 指示器宽度适配标签文本宽度(不拉伸全屏)
  • 选中标签文本加粗变色,未选中标签为灰色
  • TabBar底部有一条贯穿整个宽度的细边框,位于指示器后方

首先我们需要自定义一个Decoration来实现这个特殊的圆角指示器:

import 'package:flutter/material.dart';

class CurvedBottomIndicator extends Decoration {
  final Color color;
  final double height;
  final double radius;

  CurvedBottomIndicator({
    required this.color,
    this.height = 30,
    this.radius = 12,
  });

  @override
  BoxPainter createBoxPainter([VoidCallback? onChanged]) {
    return _CurvedBottomIndicatorPainter(color, height, radius);
  }
}

class _CurvedBottomIndicatorPainter extends BoxPainter {
  final Color color;
  final double height;
  final double radius;

  _CurvedBottomIndicatorPainter(this.color, this.height, this.radius);

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration config) {
    final Paint paint = Paint()..color = color;
    final width = config.size!.width;
    final top = offset.dy + config.size!.height - height;
    final RRect rrect = RRect.fromRectAndCorners(
      Rect.fromLTWH(offset.dx, top, width, height),
      topLeft: Radius.circular(radius),
      topRight: Radius.circular(radius),
    );
    canvas.drawRRect(rrect, paint);
  }
}

接下来是如何在TabBar中使用这个指示器,同时配置文本样式和底部边框:

TabBar(
  tabs: const [
    Tab(text: "首页"),
    Tab(text: "发现"),
    Tab(text: "我的"),
  ],
  // 配置自定义指示器
  indicator: CurvedBottomIndicator(
    color: Colors.blueAccent, // 指示器颜色
    height: 4, // 指示器高度
    radius: 2, // 圆角大小
  ),
  // 让指示器宽度适配标签内容
  indicatorSize: TabBarIndicatorSize.tab,
  // 选中标签的文本样式
  labelStyle: const TextStyle(
    fontWeight: FontWeight.bold,
    color: Colors.blueAccent,
  ),
  // 未选中标签的文本样式
  unselectedLabelStyle: const TextStyle(
    fontWeight: FontWeight.normal,
  ),
  unselectedLabelColor: Colors.grey,
  // 添加TabBar底部的细边框
  decoration: const BoxDecoration(
    border: Border(
      bottom: BorderSide(
        color: Colors.grey.shade300,
        width: 0.5,
      ),
    ),
  ),
)

这里需要注意几个关键点:

  • 设置indicatorSize: TabBarIndicatorSize.tab才能让指示器宽度匹配标签内容,而不是拉伸全屏
  • 通过BoxDecoration给TabBar添加底部边框,这个边框会自然显示在指示器后方
  • 可以通过调整CurvedBottomIndicator的height和radius参数,灵活控制指示器的高度和圆角大小
  • 文本样式分别通过labelStyle、unselectedLabelStyle、labelColor、unselectedLabelColor配置,清晰区分选中态和未选中态

这样就能完全实现你想要的TabBar效果啦!

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.07 11:03:02