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') ) ] ) );
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.
To center a widget you can use MainAxisAlignment. center method. And in this way, you can center any widget.
Flutter – Center Align Text in Text Widget To center align the text in a Text widget, provide textAlign property with value TextAlign. center .
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') ] ), ), );
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'), ), ) ], ), ), );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With