CustomSingleChildLayout: Parent-Driven Layout
CustomSingleChildLayout lets a parent widget dictate its child's size and position, ignoring the child's intrinsic size. Use it for layouts where the parent's dimensions are independent, like a custom overlay.
WHY IT EXISTS Standard layout widgets like Column or Align have predefined rules for sizing and positioning children. When those rules are too restrictive for a unique UI, you need a way to implement your own layout logic for a single child without building a complex RenderObject from scratch.
THE MENTAL MODEL Think of CustomSingleChildLayout as a picture frame where you control everything. You, through a delegate, first decide the exact size of the frame itself. Then, you tell the frame exactly where to position the child picture and what size it must be. The frame's size is decided first and never changes based on the picture you put inside it.
HOW IT WORKS You provide the widget with a child and a delegate (a SingleChildLayoutDelegate). This delegate is where you define the custom logic. You must implement methods on the delegate, primarily getSize and getPositionForChild. getSize returns the size the parent CustomSingleChildLayout should be. getPositionForChild returns the Offset (top-left corner) where the child should be placed. The key is that getSize is called before the child is laid out, so it cannot know the child's size.
WHEN TO USE IT Use this for non-standard layouts where the parent's size is known, but the child's position or constraints need to be calculated dynamically. It's perfect for creating custom tooltips or pop-up menus that must be positioned relative to another UI element, ensuring they don't render off-screen. The parent's size is determined by the available space, not the child's content.
WHEN NOT TO USE IT Do not use this if the parent's size needs to depend on the child's size. This is the widget's fundamental limitation. If you want a container that grows to wrap its child, use Container or Align. CustomSingleChildLayout enforces a one-way, parent-down sizing relationship.
ONE CANONICAL EXAMPLE Creating a custom draggable element confined to a specific area. The CustomSingleChildLayout can be the size of the confinement area. The delegate's getPositionForChild method would take the user's drag offset and return the child's new position, clamping it to stay within the parent's bounds. The parent's size is fixed, while the child's position is highly dynamic.
Read the original → api.flutter.dev
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.