CodeBlanks Logo Icon CodeBlanks

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);

Practice 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.

Starter code

main.dart
import 'package:flutter/material.dart';

// TrianglePainter sınıfını tanımla

void main() {
  // TrianglePainter örneğini al ve tipini yazdır
}

Sample solution

main.dart
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);
}

Expected output

TrianglePainter

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 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 Correct answer
  • close starts the Path
  • lineTo moves to a point without drawing

Explanation: close draws a line back to the Path's starting point and closes the shape; moveTo moves without drawing, lineTo moves while drawing.

2 Pass Paint to drawPath

Question
canvas.drawPath(path, ____);
Answer
canvas.drawPath(path, paint);

Explanation: drawPath expects a Paint object as its second parameter; a Color cannot be passed directly.

3 Path matches

Term Meaning
Path Multi-line shape
moveTo Moves the pen without drawing
lineTo Draws a line
close Closes the shape

All lessons in Advanced