Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter - How to center widget inside list view

I'm struggling with centering a widget inside listView.

I tried this, but Text('ABC') is not centered vertically. How can I achieve this?

new Scaffold(   appBar: new AppBar(),   body: new ListView(     padding: const EdgeInsets.all(20.0),     children: [       new Center(         child: new Text('ABC')       )     ]   ) ); 
like image 219
Daibaku Avatar asked Oct 25 '18 14:10

Daibaku


People also ask

How do I center widgets in Flutter?

In Flutter, to vertically center a child widget inside a Container, you can wrap the child widget with Column and add mainAxisAlignment: MainAxisAlignment. center to it.

How do you center a widget horizontally Flutter?

To center a widget you can use MainAxisAlignment. center method. And in this way, you can center any widget.

How do you center everything in Flutter?

Flutter – Center Align Text in Text Widget To center align the text in a Text widget, provide textAlign property with value TextAlign. center .


2 Answers

Vertically Center & Horizontal Center:

Scaffold(   appBar: new AppBar(),   body: Center(     child: new ListView(       shrinkWrap: true,         padding: const EdgeInsets.all(20.0),         children: [           Center(child: new Text('ABC'))         ]     ),   ), ); 

Only Vertical Center

Scaffold(   appBar: new AppBar(),   body: Center(     child: new ListView(       shrinkWrap: true,         padding: const EdgeInsets.all(20.0),         children: [           new Text('ABC')         ]     ),   ), ); 
like image 94
anmol.majhail Avatar answered Oct 22 '22 21:10

anmol.majhail


Solving this question with shrinkWrap = true is a hack. The whole point of centering widgets inside a ListView is to have bounciness and scrolling enabled. Using shrinkWrap doesn't achieve this, it looks visually correct but it behaves completely wrong.

The solution is to place a Container as the only children in the ListView, and give it a minimum height equal to the available space for the height (Use LayoutBuilder to measure the maximum height for the widget). Then as the Container's child, you can either place a Center or Column (with MainAxisAlignment.center) widget and from there you can add whatever widgets you intended to center.

Below is the code to solve the example in the question:

Scaffold(   appBar: AppBar(),   body: LayoutBuilder(     builder: (context, constraints) => ListView(       children: [         Container(           padding: const EdgeInsets.all(20.0),           constraints: BoxConstraints(             minHeight: constraints.maxHeight,           ),           child: Center(             child: Text('ABC'),           ),         )       ],     ),   ), ); 
like image 45
Lucas Chwe Avatar answered Oct 22 '22 19:10

Lucas Chwe