Flutter CustomPainter

A portrait painting style image of a pirate holding an iPhone.

by The Captain

on
May 25, 2023

Flutter CustomPainter: Drawing Custom Shapes and Designs

Flutter's CustomPainter widget provides a powerful way to create custom shapes, designs, and visual representations in a Flutter app. CustomPainter allows developers to draw on a canvas and implement complex graphics with control over lines, shapes, colors, and positioning. This tutorial will show you how to use the CustomPainter widget to draw custom shapes and designs.

Getting Started with CustomPainter

To use CustomPainter, you first need to create a new class that extends the CustomPainter class. This class should have two main methods:

  • paint()
  • shouldRepaint()

paint() is responsible for drawing on the canvas while shouldRepaint() determines whether the CustomPainter should redraw. Here's an example:


class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    // draw code here
  }

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


In this example, paint() is empty, and shouldRepaint() always returns false, indicating that the widget should only be drawn once.

Drawing on a Canvas with CustomPainter

The canvas object passed into the paint() method allows you to draw various shapes and designs onto it, such as:

  • lines
  • circles
  • rectangles
  • curves
  • and more

Here's an example of drawing a line:


class MyPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()..color = Colors.black;

    canvas.drawLine(Offset(0, 0), Offset(size.width, size.height), paint);
  }

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


This will draw a diagonal line from the top-left corner to the bottom-right corner of whatever widget it is added to.

Using CustomPainter in a Flutter Widget

After creating your CustomPainter class, you can use it in a Flutter widget using the CustomPaint widget. CustomPaint takes in a CustomPainter object and handles the drawing on the canvas for you.

Here's an example of using CustomPainter to create a line:


class MyPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: CustomPaint(
          painter: MyPainter(),
          child: Container(),
        ),
      ),
    );
  }
}


In this example, MyPainter is used as the painter for the CustomPaint object. The child property is an optional property that can be used to display child widgets on top of the canvas.

Conclusion

CustomPainter is a powerful widget for creating custom shapes and designs in Flutter apps. By extending the CustomPainter class and implementing the paint() and shouldRepaint() methods, you can draw on a canvas and create complex graphics.