Flutter 自定义点击组件(水波纹点击效果)

这篇博客介绍了如何在Flutter中自定义MaterialDesign风格的按钮水波纹效果。通过使用InkWell和Ink组件,可以实现点击按钮时的水波纹动画。然而,当子组件设置背景色或图片后,水波纹可能会消失。为解决这个问题,建议使用Stack组件,将InkWell置于顶部,以此保持水波纹效果。InkWellView是一个自定义组件,它接受子组件、点击回调、边框半径、溅色和高亮颜色等参数,提供了一种灵活的方式来定制水波纹组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Flutter中的 Material Design 风格中,点击按钮通常会出现水波纹效果。如果想自定义这种效果,可以使用 InkWell 和 Ink 组件。

  1. InkWell:一个具有水波纹效果和触摸事件处理功能的组件。它可以包裹其他组件来实现自定义的水波纹效果。

  2. Ink:用于在 InkWell 内部生成水波纹效果的组件。

但是使用inkWell自定义水波纹组件时,子组件设置背景色或背景图片后,会导致水波纹效果消失。这里使用Stack组件包裹,inkWell放在最上面。样式均由子组件确定!

class InkWellView extends StatelessWidget {
  final Widget child;
  final void Function()? onPressed;
  final BorderRadius borderRadius;
  final Color splashColor;
  final Color highlightColor;
  final Color backColor = Colors.transparent;
  final double? width, height;

  InkWellView({
    required this.child,
    this.onPressed,
    this.borderRadius = const BorderRadius.all(Radius.circular(0)),
    this.splashColor = Colors.grey,
    this.highlightColor = Colors.grey,
    this.width,
    this.height,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: width,
      height: height,
      decoration: BoxDecoration(
        borderRadius: borderRadius,
      ),
      child: Stack(
        children: [
          child,
          Positioned.fill(
            child: Material(
              type: MaterialType.transparency,
              borderRadius: borderRadius,
              child: Ink(
                color: backColor,
                child: InkWell(
                  splashColor: splashColor.withAlpha(200),
                  highlightColor: Colors.transparent,
                  borderRadius: borderRadius,
                  onTap: onPressed,
                ),
              ),
            ),
          )
        ],
      ),
    );
  }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值