RenderBox
- Flutter course
- Expert
- Lesson 12/39
- 4 min
Lay out a box with RenderBox.
RenderBox
RenderBox is a render object that uses a fixed-size box model; it derives from RenderObject. constraints carries the size bounds from the parent, and size holds its own size after layout. Boxes are always used for square/rectangular areas.
class MyBox extends RenderBox {
@override
void performLayout() {
size = constraints.biggest;
}
}BoxConstraints
BoxConstraints are the min/max width and height bounds coming from the parent. constraints.biggest returns the largest allowed size, constraints.smallest the smallest. size is assigned as a Size within these bounds.
Practice Define a RenderBox
Define MyBox as a RenderBox. In performLayout, set size = constraints.smallest. In main, create a MyBox instance and print its runtimeType.
Starter code
import 'package:flutter/rendering.dart';
// MyBox sınıfını RenderBox olarak tanımla
// performLayout'ta size'ı constraints smallest ata
void main() {
// MyBox örneği al ve runtimeType yazdır
}Sample solution
import 'package:flutter/rendering.dart';
class MyBox extends RenderBox {
@override
void performLayout() {
size = constraints.smallest;
}
}
void main() {
final box = MyBox();
print(box.runtimeType);
}Expected output
MyBox
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 When is size determined in RenderBox?
- Never
- At compile time
- During paint
- After performLayout is called Correct answer
Explanation: size is assigned inside the performLayout method; it is computed using the constraints from the parent and becomes valid once layout finishes.
2 Use constraints.smallest
final minSize = constraints.____;
final minSize = constraints.smallest;
Explanation: constraints.smallest returns the smallest allowed size; biggest returns the largest, width and height are not direct properties on BoxConstraints.
3 RenderBox matches
| Term | Meaning |
|---|---|
RenderBox |
Box render object |
constraints |
Parent bounds |
size |
Size after layout |
BoxConstraints |
Min/max bounds |