tezvyn:

CustomMultiChildLayout: A Delegate for Complex Layouts

AI-drafted, machine-checkedSource: api.flutter.devadvanced

CustomMultiChildLayout gives a delegate total control to size and position multiple children. It's for complex layouts where widgets relate to each other, like a radial menu. The key footgun: the parent's size cannot depend on the sizes of its children.

WHY IT EXISTS Flutter's standard layout widgets like Row, Column, and Stack handle most use cases. However, some UIs require such specific positioning and sizing logic for multiple children that they cannot be built with standard tools. CustomMultiChildLayout is the escape hatch for these complex, non-standard scenarios.

THE MENTAL MODEL CustomMultiChildLayout is a blank canvas for arranging multiple widgets. You provide the widgets (children) and a separate blueprint (the MultiChildLayoutDelegate). This delegate acts as a layout manager, measuring and positioning each child according to your custom rules, completely ignoring standard layout behavior. It's like giving a stage director a set of actors and a script for where they should stand and how much space they take up.

HOW IT WORKS You wrap your child widgets inside a CustomMultiChildLayout. Crucially, each child must also be wrapped in a LayoutId widget, which assigns a unique identifier. Your MultiChildLayoutDelegate uses these IDs to request specific children, measure them using layoutChild(), and position them using positionChild(). All this logic lives inside the delegate's performLayout() method. The delegate decides the final size of the parent widget.

WHEN TO USE IT Use it for layouts that are too complex for Stack or Flow. This includes a custom toolbar where an avatar overlaps the app bar, a radial menu where items are positioned on a circle, or a custom grid with irregular cell relationships. It excels when the position of one child depends on the size or position of another.

WHEN NOT TO USE IT For simpler cases, it's overkill. If you just need to overlay widgets, use Stack. For a single child, use CustomSingleChildLayout. The primary limitation is a major footgun: the parent's size cannot depend on the children's sizes. This makes it unsuitable for layouts that need to dynamically wrap their content's total size.

ONE CANONICAL EXAMPLE A common use case is creating a cascading list where each item overlaps the previous one. The delegate would iterate through the children by their IDs, calculating an increasing offset for each call to positionChild(). This creates a fan-like effect that can dynamically adjust to the number of children, something very difficult to achieve with a standard Stack or List.

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.