In flutter, how would you align different length text to the left and in center of a List view builder? I have tried column, align and text align but in vain.
There are different solutions for this. The most important thing is how your layout will look on different screen sizes.
I provided two examples, one with Padding and one with the Position widgets.
Both solutions provide the same result as shown in the screenshot below.
Let me know if it's suitable for your case.
class ExampleWithPositionWidget extends StatelessWidget {
const ExampleWithPositionWidget({
super.key,
});
final _percentageFromScreenEdge = 0.1; // 10%.
@override
Widget build(BuildContext context) {
return Stack(
children: [
Positioned(
left: MediaQuery.of(context).size.width * _percentageFromScreenEdge,
right: MediaQuery.of(context).size.width * _percentageFromScreenEdge,
top: 0,
bottom: 0,
child: Container(
color: Colors.blue.withAlpha(50),
child: ListView.builder(
itemCount: differentLengthStrings.length,
itemBuilder: (context, index) {
final item = differentLengthStrings[index];
return Text(item);
},
),
),
),
],
);
}
}
class ExampleWithPadding extends StatelessWidget {
const ExampleWithPadding({
super.key,
});
final double _horizontalPadding = 0.10; // 10% of the screen width
@override
Widget build(BuildContext context) {
final screenWidth = MediaQuery.of(context).size.width;
return Center(
child: Container(
padding: EdgeInsets.symmetric(
horizontal: screenWidth * _horizontalPadding,
),
child: Container(
color: Colors.blue.withAlpha(50),
child: Column(
children: [
Expanded(
child: ListView.builder(
itemCount: differentLengthStrings.length,
itemBuilder: (context, index) {
final item = differentLengthStrings[index];
return Text(item);
},
),
),
],
),
),
),
);
}
}