What is paint in Flutter

The paint object in Flutter helps us to paint on the screen. It’s mainly a description of the style to use when we draw on a Canvas. As a result, most APIs on Canvas take a Paint object to describe the style to use for that operation.

In our previous section, we’ve discussed how to paint in Flutter. In this section, we’ll try to learn what is paint in Flutter.

However, we need a widget that will supply us the Canvas.

Right?

Therefore, we need CustomPaint widget. It asks its painter parameter to paint on the Canvas.

Let’s take a look at the screenshot first.

Painting the background with Custom paint
Painting the background with Custom paint

Next, we examine the code of how we have created a custom paint object.

class PinkPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final height = size.height;
    final width = size.width;
    Paint paint = Paint();

    /// creating path object that will paint the background
    Path mainBackground = Path();
    mainBackground.addRect(Rect.fromLTRB(0, 0, width, height));

    /// setting color for the background
    paint.color = Colors.pink.shade800;
    canvas.drawPath(mainBackground, paint);

    /// creating another Path object that will start painting
    Path ovalPath = Path();

    ovalPath.moveTo(0, height * 0.1);

    ovalPath.quadraticBezierTo(
        width * 0.45, height * 0.35, width * 0.51, height * 0.8);

    ovalPath.quadraticBezierTo(width * 0.58, height * 0.8, width * 0.2, height);

    ovalPath.lineTo(0, height);

    ovalPath.close();

    paint.color = Colors.pink.shade500;
    canvas.drawPath(ovalPath, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return oldDelegate != this;
  }

In the above code, we have two Path objects. Based on these two path objects the Canvas object draws the design.

To do so, the CustomPaint widget takes help from CustomPainter abstract class.

Why?

Because CustomPainter again extends Listenable so that it not only gives us a canvas where we can paint on, but it creates a custom painter that repaints whenever repaint notifies listeners.

How does it take place?

Through Listenable object the Custom Painter object maintains a list of listeners.

Painters are implemented by sub-classing CustomPainter.

How did we get this effect?

We’ve wrapped the child widget with CustomPaint widget.

The CustomPaint widget normally size themselves to their child. If they do not have a child, they attempt to size themselves to the size, which defaults to Size.zero

The size must not be null.

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

Let’s see how we return our custom paint object to the painter parameter to paint on the Canvas.

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const String title = 'CustomPaint';
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: customAppBar(title),
      body: CustomPaint(
        painter: PinkPainter(),
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Container(
                padding: const EdgeInsets.all(10),
                child: Text(
                  'You have pushed the FISH this many times:',
                  style: TextStyle(
                    fontSize: 30,
                    fontWeight: FontWeight.bold,
                    color: Colors.pink.shade100,
                  ),
                ),
              ),
              Container(
                padding: const EdgeInsets.all(10),
                child: Text(
                  '$_counter',
                  style: TextStyle(
                    fontSize: 60,
                    fontWeight: FontWeight.bold,
                    color: Colors.pink.shade200,
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
        backgroundColor: Colors.pink.shade200,
      ),
    );
  }

  AppBar customAppBar(String title) {
    return AppBar(
      centerTitle: true,
      //backgroundColor: Colors.grey[400],
      flexibleSpace: Container(
        decoration: const BoxDecoration(
          gradient: LinearGradient(
            colors: [
              Colors.pink,
              Colors.grey,
            ],
            begin: Alignment.topRight,
            end: Alignment.bottomRight,
          ),
        ),
      ),
      //elevation: 20,
      titleSpacing: 80,
      leading: const Icon(Icons.menu),
      title: Text(
        title,
        textAlign: TextAlign.left,
      ),
      actions: [
        buildIcons(
          const Icon(Icons.add_a_photo),
        ),
        buildIcons(
          const Icon(
            Icons.notification_add,
          ),
        ),
        buildIcons(
          const Icon(
            Icons.settings,
          ),
        ),
        buildIcons(
          const Icon(Icons.search),
        ),
      ],
    );
  }

  IconButton buildIcons(Icon icon) {
    return IconButton(
      onPressed: () {},
      icon: icon,
    );
  }
}

For full code please visit the respective GitHub repository.

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

Courses at Educative

GitHub repository

Technical blog

Twitter

Comments

2 responses to “What is paint in Flutter”

  1. […] also changed the layout in a significant […]

  2. […] Comment Widget tree suit les principes de désign et de mise en page? […]

Leave a Reply