Flutter - How to center widget inside list view
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'),
),
)
],
),
),
);