CodeBlanks Logo Icon CodeBlanks

paint method

Draw inside the paint method.

paint method

The paint method draws the render object to the screen. It takes two parameters: PaintingContext context for the drawing context, and Offset offset for the top-left corner position. Drawing is done via context.canvas.

@override
void paint(PaintingContext context, Offset offset) {
  context.canvas.drawRect(
    offset & const Size(50, 50),
    Paint()..color = Colors.blue,
  );
}

context.canvas

PaintingContext manages the drawing context; you reach the Canvas via context.canvas. offset specifies the position in the parent tree; drawing coordinates are shifted accordingly.

Practice Define RectBox

Define RectBox as a RenderBox. In performLayout, set size = constraints.constrain(const Size(100, 50)). In paint, call context.canvas.drawRect with rect offset & const Size(100, 50) and paint Paint()..color = Colors.blue. In main, create a RectBox instance and print its runtimeType.

Starter code

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

// RectBox sınıfını RenderBox olarak tanımla
// performLayout'ta size'ı 100x50 olarak constrain et
// paint'te context.canvas ile mavi bir dikdörtgen çiz (offset ve Size(100,50))

void main() {
  // RectBox örneği al ve runtimeType yazdır
}

Sample solution

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

class RectBox extends RenderBox {
  @override
  void performLayout() {
    size = constraints.constrain(const Size(100, 50));
  }

  @override
  void paint(PaintingContext context, Offset offset) {
    context.canvas.drawRect(
      offset & const Size(100, 50),
      Paint()..color = Colors.blue,
    );
  }
}

void main() {
  final box = RectBox();
  print(box.runtimeType);
}

Expected output

RectBox

Questions and answers

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

1 What is the signature of the paint method?

  • void paint(Widget w)
  • void paint(PaintingContext context, Offset offset) Correct answer
  • void paint(BuildContext ctx)
  • void paint(Paint p)

Explanation: The paint signature is void paint(PaintingContext context, Offset offset); context.canvas gives the drawing surface and offset gives the top-left corner.

2 Use context.canvas

Question
context.____.drawRect(rect, paint);
Answer
context.canvas.drawRect(rect, paint);

Explanation: PaintingContext's canvas getter returns the drawing surface; painter, brush and surface are not properties on PaintingContext.

3 paint method matches

Term Meaning
paint Drawing method
context Drawing context
offset Top-left position
canvas Drawing surface

All lessons in Expert