Back to Posts

How to Draw a Triangle in Flutter

2 min read

Drawing a triangle in Flutter can be achieved using the CustomPainter class to define the triangle's vertices and draw it on a canvas.

Using CustomPainter

The CustomPainter class allows you to draw custom shapes, including triangles, on a canvas.

Example

import 'package:flutter/material.dart';

class TrianglePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final paint = Paint()
      ..color = Colors.green
      ..style = PaintingStyle.fill;

    final path = Path()
      ..moveTo(size.width / 2, 0)
      ..lineTo(0, size.height)
      ..lineTo(size.width, size.height)
      ..close();

    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}

class TriangleWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CustomPaint(
      size: Size(200, 200),
      painter: TrianglePainter(),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      body: Center(
        child: TriangleWidget(),
      ),
    ),
  ));
}

By using the CustomPainter class, you can easily draw triangles in your Flutter applications.