返回

构建个性十足的 TabBar Indicator,用 Flutter 实现自定义 TabBar 指示器

前端

在 Flutter 中,TabBar 是一个非常实用的控件,它可以帮助我们在屏幕上创建选项卡式导航。然而,默认的 TabBar 指示器只是一个简单的下划线,如果你想让你的应用程序更具个性化,那么你可能需要自定义 TabBar 指示器。

实现自定义 TabBar 指示器的方法有很多,其中一种方法是使用 TabBarIndicator 类。TabBarIndicator 类允许我们在 TabBar 中设置自定义的指示器。

我们可以通过继承 TabBarIndicator 类并实现其 build 方法来创建自定义的 TabBar 指示器。在 build 方法中,我们可以使用 Canvas 类来绘制自定义的指示器。

比如,我们可以创建一个简单的矩形指示器,如下所示:

import 'package:flutter/material.dart';

class CustomTabBarIndicator extends TabBarIndicator {
  @override
  Widget build(BuildContext context, TabItem<dynamic> tabItem) {
    final animation = TabBarTheme.of(context).animation!;
    final indicatorSize = TabBarTheme.of(context).indicatorSize;

    final Rect tabIndicatorRect = Rect.fromLTWH(
        tabItem.position.dx,
        tabItem.position.dy + tabItem.size.height - indicatorSize.height,
        tabItem.size.width,
        indicatorSize.height);

    return Align(
      alignment: Alignment.bottomCenter,
      child: AnimatedBuilder(
        animation: animation,
        builder: (context, child) {
          return CustomPaint(
            painter: _IndicatorPainter(
              rect: tabIndicatorRect,
              animation: animation,
            ),
          );
        },
      ),
    );
  }
}

class _IndicatorPainter extends CustomPainter {
  final Rect rect;
  final Animation<double> animation;

  _IndicatorPainter({
    required this.rect,
    required this.animation,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint();
    paint.color = Colors.blue;
    canvas.drawRRect(
        RRect.fromRectAndRadius(rect, Radius.circular(10)), paint);
  }

  @override
  bool shouldRepaint(_IndicatorPainter oldDelegate) {
    return rect != oldDelegate.rect || animation != oldDelegate.animation;
  }
}

然后,我们可以在 TabBar 中使用这个自定义的 TabBar 指示器,如下所示:

TabBar(
  indicator: CustomTabBarIndicator(),
  tabs: [
    Tab(icon: Icon(Icons.home)),
    Tab(icon: Icon(Icons.settings)),
  ],
);

这样,我们就创建了一个自定义的 TabBar 指示器,它是一个矩形。你可以根据自己的需要,自定义 TabBar 指示器的形状和颜色。

除了使用 TabBarIndicator 类来创建自定义的 TabBar 指示器之外,你还可以使用其他方法,比如使用 CustomPaint 类或者使用 ShaderMask 类。

希望这篇教程对你有所帮助。如果你有任何问题,请随时留言。