Flutter Cards:如何在Flutter中创建自定义卡片小部件

时间:2018-11-06 20:05:09

标签: flutter

我正在尝试创建一个看起来像这样的自定义卡片: enter image description here

我该如何在颤抖中实现这一目标?

这是我想要实现的:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用ClipPath自定义剪辑小部件

ClipPath(clipper: _CustomClipper(), child: Container(width: 200.0, height: 100.0, color: Colors.grey,),)

(仅以灰色容器为例)

const double _topPadding = 20.0;
const double _arcRadius = 8.0;
class _CustomClipper extends CustomClipper<Path> {
  @override
  Path getClip(Size size) {
    double point = size.width / 3 * 2;
    final path = Path()
      ..moveTo(0.0, _topPadding)
      ..lineTo(point, _topPadding)
      ..lineTo(point, _arcRadius)
      ..lineTo(point + _arcRadius, 0.0)
      ..lineTo(size.width - _arcRadius, 0.0)
      ..lineTo(size.width, _arcRadius)
      ..lineTo(size.width, size.height)
      ..lineTo(0.0, size.height)
      ..lineTo(0.0, _topPadding)
      ..addOval(Rect.fromLTRB(
          point, 0.0, point + 2 * _arcRadius, 2 * _arcRadius))
      ..addOval(Rect.fromLTRB(
          size.width - 2 * _arcRadius, 0.0, size.width, 2 * _arcRadius));

    path.close();
    return path;
  }

  @override
  bool shouldReclip(CustomClipper<Path> oldClipper) => false;
}

UPD-提升解决方案

Material(
    color: Colors.yellow,
    clipBehavior: Clip.antiAlias,
    shape: _CustomBorder(),
    elevation: 16.0, child: Container(width: 200.0, height: 100.0, child: Stack(
        children: <Widget>[
            Positioned(child: FittedBox(fit: BoxFit.scaleDown, child: Text('and a text here too'),),left: 140.0, right: 4.0, top: 4.0,),
            Positioned(child: Text('I want a text here', style: TextStyle(fontSize: 24.0),), top: 40.0, left: 4.0,)
        ],
    ),),)
...
class _CustomBorder extends BorderDirectional {
  @override
  Path getOuterPath(ui.Rect rect, {ui.TextDirection textDirection}) {
    Size size = rect.size;
    double point = size.width / 3 * 2;
    final path = Path()
      ..moveTo(0.0, _topPadding)
      ..lineTo(point, _topPadding)
      ..lineTo(point, _arcRadius)
      ..lineTo(point + _arcRadius, 0.0)
      ..lineTo(size.width - _arcRadius, 0.0)
      ..lineTo(size.width, _arcRadius)
      ..lineTo(size.width, size.height)
      ..lineTo(0.0, size.height)
      ..lineTo(0.0, _topPadding)
      ..addOval(Rect.fromLTRB(
          point, 0.0, point + 2 * _arcRadius, 2 * _arcRadius))
      ..addOval(Rect.fromLTRB(
          size.width - 2 * _arcRadius, 0.0, size.width, 2 * _arcRadius));

    path.close();
    return path;
  }
}