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])
],
),
);
}),
);
}
}
CodePudding user response:
add Allign
and allign left:
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
shrinkWrap: true,
itemCount: list.length,
itemBuilder: (context, index) {
return Align(
alignment: Alignment.centerLeft,
child: Container(
decoration:
BoxDecoration(border: Border.all(color: Colors.black)),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text('[$index]'),
const SizedBox(width: 4),
Text(list[index])
],
),
),
);
}),
);
}
CodePudding user response:
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
CodePudding user response:
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.
CodePudding user response:
By default ListView
take all avaialble width, even if you wrap your container
with Align
, this just change the item's width
not the width that ListView
takes(if you wrap your listview with colored container you will see that).
If you are not using long list, You can use SingleChildScrollView
and Column
like this:
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: list.mapIndexed((index, e) {
return Container(
decoration:
BoxDecoration(border: Border.all(color: Colors.black)),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text('[$index]'),
const SizedBox(width: 4),
Text(e)
],
),
);
}).toList(),
),
)