Flutter – how to wrap contents the row width in the ListView?

Issue

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:

enter image description here

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])
                ],
              ),
            );
          }),
    );
  }
}

Solution

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

enter image description here

Answered By – pmatatias

Answer Checked By – Candace Johnson (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *