'Flutter adding border to CustomPaint

I'm using CustomPainter to create a triangle. I want to create a triangle with a border.

My current result:
enter image description here

What I'm looking for:
enter image description here

My PaintTriangle class:

class PaintTriangle extends CustomPainter {
  final Color backgroundColor;

  PaintTriangle({
    required this.backgroundColor,
  });

  @override
  void paint(Canvas canvas, Size size) {
    final y = size.height;
    final x = size.width;

    final paint = Paint()..color = backgroundColor;
    final path = Path()
      ..moveTo(0, y)
      ..lineTo((x / 2), (y / y))
      ..lineTo(x, y);

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}


Solution 1:[1]

You can draw another paint on canvas.

class PaintTriangle extends CustomPainter {
  final Color backgroundColor;
  final Color borderColor;

  final double borderThickness;

  PaintTriangle(
      {required this.backgroundColor,
      required this.borderColor,
      this.borderThickness = 4.0});

  @override
  void paint(Canvas canvas, Size size) {
    final y = size.height;
    final x = size.width;

    final paint = Paint()..color = backgroundColor;
    final path = Path()
      ..moveTo(0, y)
      ..lineTo((x / 2), (y / y))
      ..lineTo(x, y)
      ..lineTo(0, y); //little modification to draw bottom

    final borderPaint = Paint()
      ..color = borderColor
      ..style = PaintingStyle.stroke
      ..strokeWidth = borderThickness;
    canvas.drawPath(path, paint);
    canvas.drawPath(path, borderPaint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) => true;
}

And use

 CustomPaint(
  size: Size(200, 200),
  painter: PaintTriangle(
    backgroundColor: Colors.blue,
    borderColor: Colors.red,
  ),
),

Result

image

Solution 2:[2]

you will need to make another Custom Painter for the border with the same path as the triangle.

this link will answer your question

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yeasin Sheikh
Solution 2 omar hatem