Wrap Widget Flutter: How It Works and When to Use
Wrap widget in Flutter arranges its child widgets in horizontal or vertical lines and automatically moves them to the next line when there is no more space. It is useful for creating flexible layouts that adapt to different screen sizes without overflowing.How It Works
The Wrap widget works like a row or column but with a smart twist: when the children donβt fit in one line, it wraps them onto the next line, just like words in a paragraph. Imagine you have a box of toys and you want to line them up on a shelf. If the shelf is too short, you start a new shelf below to keep all toys visible without squishing them.
This widget arranges children horizontally or vertically based on the direction property. It also lets you control spacing between items and lines, making your layout neat and organized. This behavior is great for responsive designs where screen width changes, like phones turning from portrait to landscape.
Example
This example shows a Wrap widget with colored boxes that automatically move to the next line when they reach the screen edge.
import 'package:flutter/material.dart'; void main() => runApp(const MyApp()); class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar(title: const Text('Wrap Widget Example')), body: Center( child: Wrap( spacing: 8.0, // space between items runSpacing: 4.0, // space between lines children: List.generate(10, (index) { return Container( width: 80, height: 80, color: Colors.primaries[index % Colors.primaries.length], ); }), ), ), ), ); } }
When to Use
Use the Wrap widget when you want to display a list of items that should flow into multiple lines or columns automatically. It is perfect for tags, buttons, photos, or chips that need to adjust to different screen sizes.
For example, if you have a list of categories or filters in a shopping app, Wrap helps keep them visible and nicely spaced without cutting off or requiring horizontal scrolling. It also works well for responsive layouts where fixed rows or columns might cause overflow or wasted space.
Key Points
- Wrap arranges children horizontally or vertically and wraps them to new lines when needed.
- You can control spacing between items and lines with
spacingandrunSpacing. - It helps create flexible, responsive layouts that adapt to screen size changes.
- Commonly used for tags, buttons, chips, or any group of widgets that need to flow naturally.