fluttercustom-painting

How to position a CustomPaint in a Row widget?


I'm new with flutter. I want to position a progressbar (made with custompainter) in a row but I do not know how to do it. I want all the elements of the row to be aligned, centered vertically and with the same space between them.

enter image description here

my code is :

Widget build(BuildContext context) {
return MaterialApp(
    home: Scaffold(
  body: Container(alignment: Alignment.center, child: Row(
    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
    children: <Widget>[
      Text('text1'),
      Text('text2'),
      CustomPaint(painter: progressBar(),),
      Text('text3'),
      Text('text4')
    ],
  ),) 
));

and :

class progressBar extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
Paint paint = Paint();


Radius corner =Radius.circular(8);

paint.color =Color.fromRGBO(0, 0, 0, 1);
canvas.drawRRect(RRect.fromRectAndRadius(Rect.fromLTWH(0, 0, 250, 14), corner), paint);

paint.color =Color.fromRGBO(191, 20, 28, 1);
canvas.drawRRect(RRect.fromRectAndRadius(Rect.fromLTWH(1, 2, 50, 10), corner), paint);
}

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

Solution

  • In your current code CustommPaint has a size of 0. The documentation for the CustomPaint mentions how it gets its size so you need to either provide a child with size or provide its size property(like size: Size(50, 14)). Also in the paint method you should use the Size parameter so you only draw in the space available to you and not overstep the boundaries(like you currently do):

    canvas.drawRRect(RRect.fromRectAndRadius(Rect.fromLTWH(0, 0, size.width, size.height), corner), paint);