0

I made list view with horizontal scrolling. And it is not working with out setting an height.

My code is

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text(""),
        ),
        body: Column(
          children: [
            Container(
              height: 100,
              color: Colors.red,
              child: ListView.builder(
                  itemCount: 5,
                  scrollDirection: Axis.horizontal,
                  itemBuilder: (BuildContext context, int index) {
                    return Card(
                      color: Colors.amberAccent,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                      child: Padding(
                        padding: const EdgeInsets.all(8.0),
                        child: Text("$index"),
                      ),
                    );
                  }),
            ),
            const Expanded(child: Text("Some other views")),
          ],
        ),
      ),
    );
  }
}

enter image description here

How can I leave the listview height as wrap content?

Riyas PK
  • 3,147
  • 1
  • 23
  • 29

1 Answers1

1

That's one of the things you will have to live with. If there is a list of 1 million items and each one is wrap_content and somehow one of the list item is going to be 1000px in height, flutter has no way of knowing this as it only lays out items which are going to be visible (or has potential to be visible on user interaction immediately). It doesn't build all the million items at once so we need to provide some height.

This is true for vertical lists as well. We usually don't pay attention as most apps in portrait mode have not much width so it matches parent's width without any issue.

Rahul
  • 3,529
  • 1
  • 5
  • 19