How to redraw my canvas in CustomPainter flutter

16 Views Asked by At

I am using Custom Painter to draw on image. Here's the code:

class ImageEditor extends CustomPainter {
ImageEditor({
required this.image,
});
ui.Image image;

List<Offset> points = [];
List<List<Offset>> lines = [];

final Paint painter = new Paint()
..color = Helper.primary
..strokeCap = StrokeCap.round
..strokeWidth = 5.0;

void startNewLine() {
points = [];
lines.add(points);
}

void update(Offset offset) {
points.add(offset);
}

void clearPoints() {
if (lines.isNotEmpty) {
  var index = lines.indexOf(lines.last);
  lines.removeAt(index);
}
}

@override
void paint(Canvas canvas, Size size) async {
canvas.save();
Size imageSize = Size(image.width.toDouble(), image.height.toDouble());
Rect imageRect = Offset.zero & imageSize;
Rect canvasRect = Offset.zero & size;
canvas.drawImageRect(image, imageRect, canvasRect, Paint());
canvas.restore();
for (List<Offset> line in lines) {
  for (int i = 0; i < line.length - 1; i++) {
    if (line[i] != null && line[i + 1] != null) {
      canvas.drawLine(line[i], line[i + 1], painter);
    } else if (line[i] != null && line[i + 1] == null) {
      canvas.drawPoints(PointMode.points, [line[i]], painter);
    }
  }
}
}

@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}

The issue is I have a textfield in bottomsheet. when i try to write text on it, screen gets rebuild and drawing on image get cleared..How to stop this behaviour? Even if screen is rebuild i want my drawing to be there. Canvas must not be cleared when Screen rebuilds happen.

0

There are 0 best solutions below