How to add a Spacer in a ListView

Viewed 1630

Right now I am using a column to display several widgets:

Column(
  children: [
    Text('1'),
    Text('2'),
    Spacer(),
    Text('3'),
    Text('4'),
  ],
),

So the screen looks like this:

---
 1
 2



 3
 4
---

It allows me to always align '1' and '2' at the top and '3' and '4' at the bottom of my widget independently of its size.


However, when the widget becomes too small, it overflows:

---
 1
 2
 3
---
 4  // <- Overflow

Because of this, I would like to achieve the same result with a ListView so:

  • When the widget is high enough, '1' '2' are top-aligned and '3' '4' are bottom-aligned.
  • When the widget is not high enough, there is no extra space anymore between '2' and '3', but the user can scroll down.

I couldn't manage to use a Spacer a ListView. It throws me the error:

Failed assertion: line 1940 pos 12: 'hasSize'

What would be the correct way to implement it?

1 Answers

Try adding the Text('1') and Text('2') to a Column and Text('3') and Text('4') to another Column. Then add these two columns to an Expanded parent column and main axis alignment for the parent column as spaceBetween. Similar to the code below:

  Expanded(
    ParentColumn(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children:[
        Column1(
          children: [
            Text('1'),
            Text('2'),
           ],
        ),
        Column2(
          children: [
            Text('3'),
            Text('4'),
           ],
        ),
      ],
    ),
  )
Related