Search code examples
user-interfaceflutteruser-experience

Custom Shape in Flutter


I'm trying to draw a shape like this with some text and data in it.

Required Output

I am using CustomPaint for this

CustomPaint(
  painter: new RightBox(context),
  child: container()
),
 Container container() {
   return Container(
     height: 200,
     width:  200,
     color: Colors.black,
     margin: EdgeInsets.only(left: 20),
     child: Center(child: Text("Hi Khushal",
          style: TextStyle(
            color: Colors.white
          ),
         ),)
   );
 }
class RightBox extends CustomPainter {
  RightBox(this.context);
  BuildContext context;
  @override
  void paint(Canvas canvas, Size size) {
    size = MediaQuery.of(context).size;

    Paint paint = Paint()
    ..color = Colors.black;

    Path path = Path()

      ..moveTo(size.width * 0.02 + size.width * 0.5, size.height * 0.85)
      ..lineTo(size.width * 0.05 + size.width * 0.5, size.height * 0.70)
      ..lineTo(size.width * 0.45 + size.width * 0.5, size.height * 0.67)
      ..lineTo(size.width * 0.48 + size.width * 0.5, size.height * 0.85);
    path.close();

    canvas.drawPath(path, paint);

  }

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

Output I'm getting with the above code

I want the text to be shown in the bottom right CustomPaint Widget, I am passing a child Container to the CustomPaint but instead, I'm getting a widget positioned separately in the stack. I know I'm doing something wrong, please help me achieve the UI.


Solution

  • Your painter is taking the full size of the screen. Hence, you need to align the container to put it inside the painter. Here is one way to do it. There are several ways to do it.

    You put your container and painter inside a stack widget. Align the container according to your needs. Make sure to give a few padding and margin to get a more accurate result.

    Stack(
        children: <Widget>[
          Align(
            alignment: Alignment.bottomRight,
            child: Container(
              height: 200,
                width: 200,
                alignment: Alignment.bottomRight,
                child: Center(
                  child: Text(
                    "Hi Khushal",
                    style: TextStyle(color: Colors.black),
                  ),
                )),
          ),
          CustomPaint(
            painter: RightBox(context),
          ),
        ],
      ),