美文网首页Flutter学习
Flutter | 自定义 TabBar Indicator:底

Flutter | 自定义 TabBar Indicator:底

作者: 无夜之星辰 | 来源:发表于2022-02-10 23:49 被阅读0次

最终效果:



思路:

系统提供了一个底部 indicator: underlineIndicator,它的代码很少,我们可以通过 copy + 修改 的方式调整成我们需要的样式。

代码:

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class TmdTabIndicator extends Decoration {
  const TmdTabIndicator({
    required this.borderSide,
    this.insets = EdgeInsets.zero,
  });

  final BorderSide borderSide;
  final EdgeInsetsGeometry insets;

  @override
  Decoration? lerpFrom(Decoration? a, double t) {
    if (a is TmdTabIndicator) {
      return TmdTabIndicator(
        borderSide: BorderSide.lerp(a.borderSide, borderSide, t),
        insets: EdgeInsetsGeometry.lerp(a.insets, insets, t)!,
      );
    }
    return super.lerpFrom(a, t);
  }

  @override
  Decoration? lerpTo(Decoration? b, double t) {
    if (b is TmdTabIndicator) {
      return TmdTabIndicator(
        borderSide: BorderSide.lerp(borderSide, b.borderSide, t),
        insets: EdgeInsetsGeometry.lerp(insets, b.insets, t)!,
      );
    }
    return super.lerpTo(b, t);
  }

  @override
  BoxPainter createBoxPainter([VoidCallback? onChanged]) {
    return _TmdPainter(this, onChanged);
  }

  Rect _indicatorRectFor(Rect rect, TextDirection textDirection) {
    final Rect indicator = insets.resolve(textDirection).deflateRect(rect);
    const lineWidth = 30.0;
    return Rect.fromLTWH(
      indicator.center.dx - lineWidth / 2,
      indicator.bottom - borderSide.width,
      lineWidth,
      borderSide.width,
    );
  }

  @override
  Path getClipPath(Rect rect, TextDirection textDirection) {
    return Path()..addRect(_indicatorRectFor(rect, textDirection));
  }
}

class _TmdPainter extends BoxPainter {
  _TmdPainter(this.decoration, VoidCallback? onChanged) : super(onChanged);

  final TmdTabIndicator decoration;

  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    assert(configuration.size != null);
    final Rect rect = offset & configuration.size!;
    final TextDirection textDirection = configuration.textDirection!;
    final Rect indicator = decoration
        ._indicatorRectFor(rect, textDirection)
        .deflate(decoration.borderSide.width / 2.0);
    final Paint paint = decoration.borderSide.toPaint()
      ..strokeCap = StrokeCap.round;
    canvas.drawLine(indicator.bottomLeft, indicator.bottomRight, paint);
  }
}

相关文章

网友评论

    本文标题:Flutter | 自定义 TabBar Indicator:底

    本文链接:https://www.haomeiwen.com/subject/sqoifrtx.html