【问题标题】:How to implement lines inside an AppBar?如何在 AppBar 中实现线条?
【发布时间】:2022-10-23 22:35:27
【问题描述】:

我想知道是否有可能(如果我能做到这一点)在 AppBar 中实现如下图所示的行: 我在 Figma 上进行了设计,我想在 Flutter 中复制它

【问题讨论】:

  • 线条是否透明,反射背景?
  • 是的,但我可以设置相同的颜色
  • 尝试使用 Path.combine(PathOperation.difference, 的 CustomPaint 或 ClipPath

标签: flutter dart flutter-layout


【解决方案1】:

我正在使用ClipPath 来获得路径,您可以在此路径中使用CustomPaint。接下来创建实现PreferredSizeWidget 的新小部件,将其放置在apBar

class AppBarClipPath extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    const radius = Radius.circular(24);
    Path bgPath = Path()
      ..addRRect(
        RRect.fromRectAndCorners(Rect.fromLTRB(0, 0, size.width, size.height),
            bottomRight: radius, bottomLeft: radius),
      );

    ///middle curve
    const thickness = 10.0;
    Path middleCurve = Path()
      ..moveTo(20, size.height)
      ..quadraticBezierTo(
          0, size.height * .3, size.width * .7, size.height * .5)
      ..quadraticBezierTo(size.width * .9, size.height * .5, size.width - 20, 0)
      ..lineTo(size.width - 20 + thickness, 0)
      ..quadraticBezierTo(size.width, size.height * .5, size.width * .7,
          size.height * .5 + thickness)
      ..quadraticBezierTo(0, size.height * .4, 20 + thickness, size.height)
      ..lineTo(size.width, size.height);

    return Path.combine(PathOperation.difference, bgPath, middleCurve);
  }

  @override
  bool shouldReclip(covariant CustomClipper<Path> oldClipper) => false;
}
class MyCustomAppBar extends StatelessWidget implements PreferredSizeWidget {
  const MyCustomAppBar({super.key});

  @override
  Widget build(BuildContext context) {
    return ClipPath(
      clipper: AppBarClipPath(),
      child: Container(
        color: Colors.deepPurple,
      ),
    );
  }

  @override
  Size get preferredSize => const Size.fromHeight(200);
}

并使用

return Scaffold(
  appBar: MyCustomAppBar(),

如您所见,它需要在quadraticBezierTo 上进行改进,但您已经有了创建它的概念。

【讨论】:

  • 而不是 appBar: MyCustomAppBar() 使用内置的 ApoBar 类,因为它具有 shape 属性
  • 我曾考虑过这一点,但后来我认为对于新手来说,有些人可能会害怕覆盖 ShapeBorder 方法(我可能错了)。我认为我的重点转移到了创建一个单独的小部件上。是的,我错过了 Appbar 上的形状,想到了 Container。
  • 但是这样的 Container 几乎是没用的:它是扁平的,没有动作,没有返回按钮……
  • 最有趣的是它提供了“形状变形” - 试试上面的代码并按下中心按钮,你会看到 appbar 的形状是如何变化的 - 你所要做的就是打电话给setState
  • 而不是用 5 种方法扩展 ShapeBorder,而是扩展 SimpleShapeBorder,您只需实现一个 getClip 方法 - 就像在 CustomClipper 中一样
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-02
  • 2020-09-14
  • 1970-01-01
  • 1970-01-01
  • 2011-09-19
相关资源
最近更新 更多