Ali
Ali

Reputation: 267077

Centering layout in Flutter

If I use the following structure in the Scaffold:

  body: Container(
      alignment: Alignment.center,
      child:
        Text('Test')  
  )

Then the text is vertically and centrally structured, as I want. But if I do the following:

body: Container(
      alignment: Alignment.center,
      child:
        ListView(
          children:people.map(person).toList(),
        ),

  )

Then the ListView is stuck to the top left of the body and isn't centered.

Why is that, and how can I center the ListView the same way that Text was centered?

Upvotes: 0

Views: 54

Answers (2)

Code on the Rocks
Code on the Rocks

Reputation: 17596

Vertical

body: Container(
  alignment: Alignment.center,
  child:
    ListView(
      shrinkWrap: true,
      children:people.map(person).toList(),
    ),
 )

Horizontal

ListView(
    shrinkWrap: true,
    children: [
      Row(
         mainAxisAlignment: MainAxisAlignment.center,
         children: [
            Text('text'),
         ],
       ),
       Text('text'),
       Text('text'),
     ],
   ),

enter image description here

Upvotes: 1

Eng
Eng

Reputation: 1714

It's because ListView take all the space available. To tell Listview to take only children sizes, add property "shrinkWrap" to true.

Center(
  child: ListView(
    shrinkWrap: true,
    children: <Widget>[
      Center(
        child: Text("Hello world !"),
      ),
    ],
  ),
)

Upvotes: 1

Related Questions