Flutter
Path
Build polylines and complex shapes with Path.
What is Path?
Path is a way to combine multiple lines and curves into a single shape. moveTo goes to a starting point, lineTo draws a line from the current point to a new one. Finally, you draw the Path with a Paint using canvas.drawPath.
final path = Path();
path.moveTo(10, 10);
path.lineTo(90, 10);
path.lineTo(50, 90);
path.close();
canvas.drawPath(path, paint);
Polygons with Path
With Path you can easily draw polygons like triangles and stars. Start with moveTo, add corners with successive lineTo calls, and close with close. To fill the Path, set the Paint's style to PaintingStyle.fill.
final paint = Paint()
..color = Colors.green
..style = PaintingStyle.fill;
final triangle = Path()
..moveTo(50, 10)
..lineTo(90, 90)
..lineTo(10, 90)
..close();
canvas.drawPath(triangle, paint);
Exercise Draw a triangle with Path
Write the paint method in TrianglePainter. Using Path, draw a blue filled triangle with vertices (10,90), (90,90), (50,10). In main, take an instance and print its type.
Show example solution
import 'package:flutter/material.dart';
class TrianglePainter extends CustomPainter {
@override
void paint(Canvas canvas, Size size) {
final paint = Paint()
..color = Colors.blue
..style = PaintingStyle.fill;
final path = Path();
path.moveTo(10, 90);
path.lineTo(90, 90);
path.lineTo(50, 10);
path.close();
canvas.drawPath(path, paint);
}
@override
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
void main() {
final painter = TrianglePainter();
print(painter.runtimeType);
}
Test yourself
-
Which of the following is true?
- moveTo draws a line to a point
- close draws a line back to the start and closes the shape
- close starts the Path
- lineTo moves to a point without drawing
Show answer
close draws a line back to the start and closes the shape — close draws a line back to the Path's starting point and closes the shape; moveTo moves without drawing, lineTo moves while drawing.
-
Pass Paint to drawPath
canvas.drawPath(path, ____);
Show answer
canvas.drawPath(path, paint);
-
Path matches
- Path
- Multi-line shape
- moveTo
- Moves the pen without drawing
- lineTo
- Draws a line
- close
- Closes the shape
Next lesson: Summary - CustomPainter