sachintha
sachintha

Reputation: 45

How to create a flutter percentage indicator with a custom border stroke

I am going to make this widget in my app but I have no idea how to do that. enter image description here

How can I achieve this? I've tried percent_indicator package in Flutter, but the main problem is that we have a limited amount of options.

Upvotes: 0

Views: 610

Answers (1)

Jared Anderton
Jared Anderton

Reputation: 1026

Credit for drawing the drawing the dashed border to this answer

class DashedProgressIndicator extends CustomPainter {
  final double percent;
  final double strokeWidth;

  DashedProgressIndicator({ this.percent = 0, this.strokeWidth = 5});

  final paint1 = Paint()
    ..color = Colors.grey[300]!
    ..style = PaintingStyle.stroke;

  final paint2 = Paint()
    ..color = Colors.grey
    ..style = PaintingStyle.stroke
    ..strokeCap = StrokeCap.round;

  @override
  void paint(Canvas canvas, Size size) {
    Offset center = Offset(size.width / 2, size.height / 2);
    double radius = min(size.width / 2, size.height / 2);

    final dashSize = (size.width *0.0004) / 2;
    double arcAngle = 2 * pi * dashSize;

    // draw dashes
    for (var i = 0; i < 24; i++) {
      final init = (-pi / 2)*(i/6);

      canvas.drawArc(
          Rect.fromCircle(center: center, radius: radius - strokeWidth / 2),
          init, arcAngle, false, paint1..strokeWidth = strokeWidth);
    }

    // draw progress
    canvas.drawArc(
        Rect.fromCircle(center: center, radius: radius - strokeWidth / 2),
        (-pi / 2), 2 * pi * percent, false, paint2..strokeWidth = strokeWidth);
  }
  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return true;
  }
}

Usage:

CustomPaint(
  painter: DashedProgressIndicator(percent: 25/100),
  size: const Size(100, 100),
),

Produces: enter image description here

Upvotes: 1

Related Questions