π§± Flutter child vs children Explained β With Examples!
When building UI in Flutter, you’ll quickly notice two properties: child and children. These look similar but are used differently β and mixing them up can cause frustrating errors. Letβs break it down clearly!
πΉ Whatβs the Difference?
child: Used for a single widget
children: Used for a list of widgets
πΉ When to Use child (Single Widget)
Widgets like Container, Center, and Padding use child because they only hold one widget inside.
Container(
padding: EdgeInsets.all(16),
child: Text("I am a child"),
)
πΉ When to Use children (Multiple Widgets)
Widgets like Row, Column, and Stack use children because they layout multiple widgets.
Row(
children: [
Icon(Icons.star),
SizedBox(width: 10),
Text("I am a child too!"),
],
)
πΉ Error Example: Misusing children
Container(
children: [ // β ERROR
Text("This will fail"),
Text("Container only takes child"),
],
)
π§ Tips to Remember
- βοΈ If it holds only one widget β use
child - βοΈ If it holds many widgets β use
children - βοΈ Think: Box = child, Shelf = children
- βοΈ Let Flutterβs red error lines help you debug!
πΉ Wrapping Multiple Widgets in a child Widget
When a widget only allows one child but you want to include multiple widgets, wrap them inside a Column or Row.
Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Hello'),
Text('World'),
],
),
)
π Summary Table
| Widget | child |
children |
Notes |
|---|---|---|---|
| Container | β | β | Single box element |
| Center | β | β | Centers one widget |
| Column | β | β | Vertical layout |
| Row | β | β | Horizontal layout |
| Stack | β | β | Overlapping layout |
| Padding | β | β | Adds space around one widget |
| ListView | β | β | Scrollable list |
Now that you understand child vs children, your Flutter layouts will be cleaner and more efficient. Keep coding and experimenting β Flutter will guide you with errors and suggestions!
