Search code examples
flutterdartpaintcustom-painting

How to create a custom container with rounded edges in flutter?


I am trying to create a custom container with round edges but not able to make the corners round. current image I just want to make the corners of green container round.

class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    var paint = Paint()
      ..color = Colors.green.withOpacity(0.8)
      ..strokeWidth = 5
      ..strokeCap = StrokeCap.round;

    final shapeBounds = Rect.fromLTRB(0, 0, size.width, size.height);

    final path = Path()
      ..moveTo(shapeBounds.left + 10, shapeBounds.top) //3
      ..lineTo(shapeBounds.bottomLeft.dx + 10,shapeBounds.bottomLeft.dy) 
      ..lineTo(shapeBounds.bottomRight.dx,shapeBounds.bottomRight.dy - size.height * 0.12)
      ..lineTo(shapeBounds.topRight.dx - 20,
          shapeBounds.topRight.dy + size.height * 0.12) //7
      ..close();

    canvas.drawPath(path, paint);

  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return false;
  }
}

Solution

  • You can use ClipPath. Use a Custom Clipper in it. In the Custom Clipper, while drawing the path use quadraticBezierTo.

    enter image description here

    class MyContainer extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return ClipPath(
          clipper: MyClipper(),
          child: Container(
            child: Text("Dummy Text"),
            alignment: Alignment.center,
            color: Colors.green,
            width: 200,
            height: 200,
          ),
        );
      }
    }
    
    class MyClipper extends CustomClipper<Path> {
      Path getClip(Size size) {
        final path = Path();
        path
          ..lineTo(0.0, size.height * 0.1)
          ..quadraticBezierTo(0, 0, size.width * 0.1, 0)
          ..lineTo(size.width * 0.8, size.height * 0.12)
          ..quadraticBezierTo(size.width * 0.9, size.height * 0.15,
              size.width * 0.9, size.height * 0.2)
          ..lineTo(size.width, size.height * 0.9)
          ..quadraticBezierTo(
              size.width, size.height, size.width * 0.9, size.height)
          ..lineTo(size.width * 0.2, size.height * 0.9)
          ..quadraticBezierTo(size.width * 0.1, size.height * 0.9, size.width * 0.1,
              size.height * 0.8)
          ..close();
        return path;
      }
    
      @override
      bool shouldReclip(CustomClipper oldClipper) {
        return false;
      }
    }