I want to draw a vertical list.
Each item in list should be filled only wrapped size.
But my code draw the list items with full width like:
I tried to use MainAxisSize.min
but it doesn’t work.
class HomePage extends StatelessWidget {
HomePage({super.key});
final List<String> list = ["apple", "banana", "cat", "dragon"];
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
shrinkWrap: true,
itemCount: list.length,
itemBuilder: (context, index) {
return Container(
decoration:
BoxDecoration(border: Border.all(color: Colors.black)),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text('[$index]'),
const SizedBox(width: 4),
Text(list[index])
],
),
);
}),
);
}
}
4
Answers
More of a workaround: depending on the layout seeked, either place the ListView into a Row or put another widget at the end of the row.
By default
ListView
take all avaialble width, even if you wrap yourcontainer
withAlign
, this just change theitem's width
not the width thatListView
takes(if you wrap your listview with colored container you will see that).If you are not using long list, You can use
SingleChildScrollView
andColumn
like this:Add
Align
and align left:because you use
ListView
, the child will will fill the width.if you want to show not much data, consider use
SingleChildScrollView
i wrote an article here to compare them and explain when to use it
https://medium.com/easyread/my-october-flutter-notes-2-6e0c78cf2e56