261

I have a Column widget with two TextField widgets as children and I want to have some space between both of them.

I already tried mainAxisAlignment: MainAxisAlignment.spaceAround, but the result was not what I wanted.

Dave
  • 28,833
  • 23
  • 113
  • 183
Sachin Soma
  • 3,432
  • 2
  • 10
  • 18

27 Answers27

331

You can use Padding widget in between those two widget or wrap those widgets with Padding widget.

Update

SizedBox widget can be use in between two widget to add space between two widget and it makes code more readable than padding widget.

Ex:

Column(
  children: <Widget>[
    Widget1(),
    SizedBox(height: 10),
    Widget2(),
  ],
),
Viren V Varasadiya
  • 25,492
  • 9
  • 45
  • 61
176

You can put a SizedBox with a specific height between the widgets, like so:

Column(
  children: <Widget>[
    FirstWidget(),
    SizedBox(height: 100),
    SecondWidget(),
  ],
),

Why to prefer this over wrapping the widgets in Padding? Readability! There is less visual boilerplate, less indention and the code follows the typical reading-order.

Marcel
  • 8,831
  • 4
  • 39
  • 50
  • Adding a sized box is like adding an empty view right ? would nt that lead to any problems ? – user5381191 Sep 29 '20 at 18:45
  • `SizedBox` is just a normal widget that has a desired size it tries to be during layout, but doesn't render anything. All the leaf widgets like Text or Container are empty too, so that's okay. – Marcel Oct 01 '20 at 13:53
141

you can use Wrap() widget instead Column() to add space between child widgets.And use spacing property to give equal spacing between children

Wrap(
  spacing: 20, // to apply margin in the main axis of the wrap
  runSpacing: 20, // to apply margin in the cross axis of the wrap
  children: <Widget>[
     Text('child 1'),
     Text('child 2')
  ]
)
Mahdi Tohidloo
  • 2,968
  • 1
  • 17
  • 17
137

There are many ways of doing it, I'm listing a few here.

  1. Use SizedBox and provide some height:

     Column(
       children: <Widget>[
         Widget1(),
         SizedBox(height: 10), // <-- Set height
         Widget2(),
       ],
     )
    
  2. Use Spacer

     Column(
       children: <Widget>[
         Widget1(),
         Spacer(), // <-- Spacer
         Widget2(),
       ],
     )
    
  3. Use Expanded

     Column(
       children: <Widget>[
         Widget1(),
         Expanded(child: SizedBox.shrink()), // <-- Expanded
         Widget2(),
       ],
     )
    
  4. Set mainAxisAlignment

     Column(
       mainAxisAlignment: MainAxisAlignment.spaceAround, // <-- alignments
       children: <Widget>[
         Widget1(),
         Widget2(),
       ],
     )
    
  5. Use Wrap

     Wrap(
       direction: Axis.vertical, 
       spacing: 20, // <-- Spacing between children
       children: <Widget>[
         Widget1(),
         Widget2(),
       ],
     )
    
CopsOnRoad
  • 237,138
  • 77
  • 654
  • 440
37

Just use padding to wrap it like this:

Column(
  children: <Widget>[
  Padding(
    padding: EdgeInsets.all(8.0),
    child: Text('Hello World!'),
  ),
  Padding(
    padding: EdgeInsets.all(8.0),
    child: Text('Hello World2!'),
  )
]);

You can also use Container(padding...) or SizeBox(height: x.x). The last one is the most common but it will depents of how you want to manage the space of your widgets, I like to use padding if the space is part of the widget indeed and use sizebox for lists for example.

dmarquina
  • 3,728
  • 1
  • 28
  • 28
25

I don't see this solution here, so just for the sake of completeness I'll post it.

You can also wrap children with Padding using map:

Column(
      children: [Text('child 1'), Text('child 2')]
          .map(
            (e) => Padding(
              padding: const EdgeInsets.all(8),
              child: e,
            ),
          )
          .toList(),
    );
eeqk
  • 3,492
  • 1
  • 15
  • 22
  • 1
    This is a better way than adding ```sizedBox()``` after each widget. – abrsh Apr 10 '21 at 12:49
  • 1
    @abrsh it's useful sometimes, yet it doesn't really add the space **between** items, but around them. – mip Sep 27 '21 at 10:45
10

I also wish there was some built-in way in Flutter to do this. Like a parameter you could pass to Column or Row. Sometimes you don't want padding around every element but you want space between them. Especially if you have more than two children, it's kind of tedious to write something like

const double gap = 10;
return Column(
  children: [
    Text('Child 1'),
    SizedBox(height: gap),
    Text('Child 2'),
    SizedBox(height: gap),
    Text('Child 3'),
    SizedBox(height: gap),
    Text('Child 4'),
  ],
);

However, I've came up with one quick (not perfect) solution:

Add this somewhere in your project (only once):

extension ListSpaceBetweenExtension on List<Widget> {
  List<Widget> withSpaceBetween({double? width, double? height}) => [
    for (int i = 0; i < length; i++)
      ...[
        if (i > 0)
          SizedBox(width: width, height: height),
        this[i],
      ],
  ];
}

And from now on whenever you have a Row or a Column, you can write

Column(
  children: [
    Text('Child 1'),
    Text('Child 2'),
    Text('Child 3'),
    Text('Child 4'),
  ].withSpaceBetween(height: 10),
),

When using Row you'll have to replace 'height' with 'width'.

kynnysmatto
  • 3,665
  • 23
  • 29
  • 1
    This is the best answer in my opinion. Clear to read, concise, and doesn't leave leading or trailing spaces like the `map` based solutions. – jayjw Oct 08 '22 at 20:35
  • I like this answer, but you can improve performance for larger lists by using adding the first element and then iterating from index 1 (instead of zero) `[if (isNotEmpty) this[0], for (int i = 1; i < length; i++) ...[SizedBox(width: width, height: height), this[i]]]`. This way element 0 is added and all remaining elements do not require an if check. – Kenten Fina Dec 15 '22 at 13:43
  • This extension is brilliant and should become the accepted answer. It is particularly valuable when you just want to pass a list of widgets to your column in the first place, because you don't have the option to add the `SizedBox`es manually in that case even if you wanted to. – Duncan Babbage Apr 28 '23 at 00:55
9
Column(
  children: <Widget>[
    FirstWidget(),
    Spacer(),
    SecondWidget(),
  ]
)

Spacer creates a flexible space to insert into a [Flexible] widget. (Like a column)

Bolling
  • 3,954
  • 1
  • 27
  • 29
user9139407
  • 964
  • 1
  • 12
  • 25
  • 5
    Please add some explanation to your answer to help others understand it better. Code only answers are considered impolite and it may not help the OP understand the problem that you are trying to help with. – Michael Aug 01 '19 at 01:59
7

The same way SizedBox is used above for the purpose of code readability, you can use the Padding widget in the same manner and not have to make it a parent widget to any of the Column's children

Column(
  children: <Widget>[
    FirstWidget(),
    Padding(padding: EdgeInsets.only(top: 40.0)),
    SecondWidget(),
  ]
)
Al-Ameen
  • 149
  • 3
  • 4
6

If you don't wanna wrap Padding with every widget or repeat SizedBox.

Try this:

Column(
        children: [
          Widget(),
          Widget(),
          Widget(),
          Widget(),
        ]
            .map((e) => Padding(
                  child: e,
                  padding: const EdgeInsets.symmetric(vertical: 10),
                ))
            .toList(),
      ),

That will warp all the widgets with padding without repetition.

Unes
  • 312
  • 7
  • 12
4

Columns Has no height by default, You can Wrap your Column to the Container and add the specific height to your Container. Then You can use something like below:

Container(
   width: double.infinity,//Your desire Width
   height: height,//Your desire Height
   child: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
         Text('One'),
         Text('Two')
      ],
   ),
),
Ali Esfandiari
  • 316
  • 4
  • 13
3

You can solve this problem in different way.

If you use Row/Column then you have to use mainAxisAlignment: MainAxisAlignment.spaceEvenly

If you use Wrap Widget you have to use runSpacing: 5, spacing: 10,

In anywhere you can use SizeBox()

Md.Tarikul Islam
  • 1,241
  • 1
  • 14
  • 16
3

Inspired by https://stackoverflow.com/a/70993832/14298786, use extension on List<Widget> to add the SizedBox:

extension on List<Widget> {
  List<Widget> insertBetweenAll(Widget widget) {
    var result = List<Widget>.empty(growable: true);
    for (int i = 0; i < length; i++) {
      result.add(this[i]);
      if (i != length - 1) {
        result.add(widget);
      }
    }
    return result;
  }
}

Use like this:

Column(children: [
  Widget1(),
  Widget2(),
  Widget3(),
].insertBetweenAll(SizedBox(height: 20)))
Yang_____
  • 117
  • 8
2

You can also use a helper function to add spacing after each child.

List<Widget> childrenWithSpacing({
  @required List<Widget> children,
  double spacing = 8,
}) {
  final space = Container(width: spacing, height: spacing);
  return children.expand((widget) => [widget, space]).toList();
}

So then, the returned list may be used as a children of a column

Column(
  children: childrenWithSpacing(
    spacing: 14,
    children: [
      Text('This becomes a text with an adjacent spacing'),
      if (true == true) Text('Also, makes it easy to add conditional widgets'),
    ],
  ),
);

I'm not sure though if it's wrong or have a performance penalty to run the children through a helper function for the same goal?

refik
  • 458
  • 6
  • 11
2

Column widget doesn't have its own height, it just expanded as we added inside the children widget. for if you need the same space between multiple widgets so,

Container(
   width: double.infinity,
   height: height,
   child: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
         Text('One'),
         Text('Two'),
         Text('Three'),
         Text('Four')
      ],
   ),
),

or just added custom space between them by using SizeBox, Spacer, or widget, like this

Column(
   children: <Widget>[
         Text('One'),
         SizedBox(height: 20), 
         Text('Two'),
         SizedBox(height: 40), 
         Text('Three'),
         SizedBox(height: 30), 
         Text('Four')
   ],
 ),
Shirsh Shukla
  • 5,491
  • 3
  • 31
  • 44
1
Column(children: <Widget>[
   Container(margin: EdgeInsets.only(top:12, child: yourWidget)),
   Container(margin: EdgeInsets.only(top:12, child: yourWidget))
]);
Bhargav Sejpal
  • 1,352
  • 16
  • 23
1

Adding multiple sized boxes gets tedious if you have too many children in a column, row, listView, etc., and if you have to do the same thing in many places in your application.

You can use the following utils to encapsulate the logic of adding these sized boxes:

List<Widget> addHorizontalSpaceBetweenElements(double space, List<Widget> widgets) {
  return _addSpaceBetweenElements(widgets, () => SizedBox(width: space));
}

List<Widget> addVerticalSpaceBetweenElements(double space, List<Widget> widgets) {
  return _addSpaceBetweenElements(widgets, () => SizedBox(height: space));
}

List<Widget> _addSpaceBetweenElements(List<Widget> widgets, ValueGetter<SizedBox> sizedBoxGetter) {
  if (widgets.isEmpty || widgets.length == 1) {
    return widgets;
  }
  List<Widget> spacedWidgets = [widgets.first];
  for (var i = 1; i < widgets.length - 1; i++) {
    spacedWidgets.add(sizedBoxGetter());
    spacedWidgets.add(widgets[i]);
  }
  spacedWidgets.add(sizedBoxGetter());
  spacedWidgets.add(widgets.last);
  return spacedWidgets;
}


And you use them like this:

Column(
  children: addVerticalSpaceBetweenElements(5, [
    Text(),
    Text(),
  Row(children: addHorizontalSpaceBetweenElements(5, [
    Text(),
    Text(),
  ])),
  ]));
1
**// provide fixed space defined in sizedbox**


 Column(
     children: [
          widget1(),
          sizedbox(height:20), 
          widget2()
        ] 
     )

**// Provides equal space between childs** 

Column(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
     widget1(),
     widget2()
   ] 
)
Ram Shukla
  • 21
  • 3
0

You may have to use SizedBox() widget between your column's children. Hope that'll be usefull

Issa
  • 49
  • 5
0

Extract the input field widgets into a custom widget that is wrapped in padding or a container with padding (assuming symmetrical spacing).

Having sized boxes in-between every column child (as suggested in other answers) is not practical or maintainable. If you wanted to change the spacing you would have to change each sized box widget.

// An input field widget as an example column child
class MyCustomInputWidget extends StatelessWidget {
  const MyCustomInputWidget({Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    // wrapping text field in container
    return Container(
      // here is the padding :)
      padding: EdgeInsets.symmetric(vertical: 10),
      child: TextField(...)
    );
  }
}

...then the column in the parent class

column(
  children: <Widget>[
    MyCustomInputWidget(),
    SizedBox(height: 10),
    MyCustomInputWidget(),
  ],
),

Obviously you would want the custom widget to have some sort of constructor to handle different field parameters.

knary
  • 301
  • 2
  • 5
0

Another alternative I'm surprised isn't listed here is to simply use ListView.separated. I use this quite a lot for lists, often using const Divider() as a material-style separator line for the spacer.

List<Widget> yourListOfWidgets = [
  const Text("Foo"),
  const Text("Bar"),
];
    
return ListView.separated(
  itemCount: yourListOfWidgets.length,
  itemBuilder: (context, index) => yourListOfWidgets[index],
  separatorBuilder: (context, index) => const SizedBox(height: 10),
)
James Allen
  • 6,406
  • 8
  • 50
  • 83
0

Basically all of the above answers are totally fine for small pieces of UI but if you are looking for a reusable and clean way to place a separator widget inside of a column, this might be what you are looking for:

class SeparatedColumn extends Column {
  SeparatedColumn({
    Key? key,
    MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
    MainAxisSize mainAxisSize = MainAxisSize.max,
    CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
    TextDirection? textDirection,
    VerticalDirection verticalDirection = VerticalDirection.down,
    TextBaseline? textBaseline,
    Widget? separator,
    required List<Widget> children,
  }) : super(
          key: key,
          children: List.generate(
            children.length * 2 - 1,
            (index) => index % 2 == 0
                ? children[index ~/ 2]
                : separator ?? const SizedBox.shrink(),
          ),
          mainAxisAlignment: mainAxisAlignment,
          mainAxisSize: mainAxisSize,
          crossAxisAlignment: crossAxisAlignment,
          textDirection: textDirection,
          verticalDirection: verticalDirection,
          textBaseline: textBaseline,
        );
}
Matteo
  • 179
  • 1
  • 8
-1

The sized box will not help in the case, the phone is in landscape mode.

body: Column(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
        Expanded(
           child: Container(
            margin: EdgeInsets.all(15.0),
            decoration: BoxDecoration(
              color: Color(0xFF1D1E33),
              borderRadius: BorderRadius.circular(10.0),
            ),
          ),
        ),
      ],
     )
Mendax
  • 11
  • 3
-1

Here's another option involving a for loop.

Column(
  children: <Widget>[
    for (var i = 0; i < widgets.length; i++)
      Column(
        children: [
          widgets[i], // The widget you want to create or place goes here.
          SizedBox(height: 10) // Any kind of padding or other widgets you want to put.
        ])
  ],
),
Antis
  • 1
  • 1
-1

You can try this :


import 'package:flutter/material.dart';

class CustomColumn extends Column {
  CustomColumn({
    Key? key,
    MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
    MainAxisSize mainAxisSize = MainAxisSize.max,
    CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
    TextDirection? textDirection,
    VerticalDirection verticalDirection = VerticalDirection.down,
    TextBaseline? textBaseline,
    List children = const [],
    EdgeInsetsGeometry? rowPadding,
  }) : super(
          children: children.map((e) => Padding(padding : rowPadding ?? EdgeInsets.only(bottom:12), child : e)).toList(),
          key: key,
          mainAxisAlignment: mainAxisAlignment,
          mainAxisSize: mainAxisSize,
          crossAxisAlignment: crossAxisAlignment,
          textDirection: textDirection,
          verticalDirection: verticalDirection,
          textBaseline: textBaseline,
        );
}

and call


CustomColumn(children: [
                    item1,
                    item2,
                    item3,
                  ])
fefe
  • 19
  • 5
-1

You can use Padding to wrap each child widget, and then set the top or bottom of Padding.

If you don’t want to write a lot of the same numbers, you can do it like this:

Column(
  children: [
    child1, 
    child2, 
    ..., 
    childN
  ].map((e) => Padding(padding: EdgeInsets.only(top: 10), child: e)).toList()
);
jqgsninimo
  • 6,562
  • 1
  • 36
  • 30
-1

It's best to use the Wrap widget instead of a column or row.

Wrap( spacing: 10, runSpacing: 10, children:[], )

  • This does not directly answer the poster's question. There are different opinions on what is the best. – Roslan Amir Feb 16 '22 at 04:08
  • 1
    As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 16 '22 at 04:09