tezvyn:

Flutter's Wrap Widget: The Row That Won't Overflow

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

Flutter's Wrap widget is like text-wrapping for your UI. It arranges children in a row or column, automatically flowing them onto a new line when space runs out. It's perfect for dynamic lists of tags or chips.

WHY IT EXISTS A standard Row or Column will crash your app with a pixel overflow error if its children are too large for the available space. Wrap was created to provide a flexible layout that automatically handles this by moving content to a new line, just like text in a document, preventing crashes.

THE MENTAL MODEL Think of Wrap as text-wrapping, but for widgets. It lays out children one after another in a line. When it hits the edge of the container and the next widget won't fit, it simply starts a new line below (or next to it, if the direction is vertical) and continues placing widgets there.

HOW IT WORKS Wrap places children along a main axis, defined by its direction property (usually horizontal). It attempts to place each child next to the previous one. If there isn't enough space, it creates a new "run" (a new line or column). You control the gap between children in the same run with spacing, and the gap between the runs themselves with runSpacing. You can also control the alignment of children within a run (alignment) and the alignment of the runs within the Wrap widget itself (runAlignment).

WHEN TO USE IT Use Wrap when you have a variable number of children that need to be laid out linearly but might not all fit on one line. It's perfect for a list of user-selected tags, a gallery of small photo thumbnails, or a row of action buttons in a dialog that needs to be responsive to different screen sizes.

WHEN NOT TO USE IT Do not use Wrap if you need children to stay in a single, scrollable line; use a ListView with scrollDirection: Axis.horizontal for that. If you know your items will always fit and you need the specific alignment controls of Row or Column (like spaceBetween), those widgets can be simpler.

ONE CANONICAL EXAMPLE A common use case is displaying a set of Chip widgets for user-selectable filters. As the user selects more filters, new chips are added. Wrap ensures they flow neatly onto multiple lines if the screen is too narrow to display them all in a single row, preventing any overflow errors.

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.