Home > Back-end >  Why horizontal Listview in flutter requires a parent with fixed height
Why horizontal Listview in flutter requires a parent with fixed height

Time:12-01

I have a horizontal Listview which is wrapped with sizebox

SizedBox(
  width: Get.width,
  height: 50,
  child: Obx(
    () => ListView.separated(
      shrinkWrap: true,
      padding: Margin.h16,
      scrollDirection: Axis.horizontal,
      itemBuilder: _itemCategoryBuilder,
      separatorBuilder: separatorBuilder,
      itemCount: controller.categories.length,
    ),
  ),
);

Why ListView doesn't calculate its height from children height. Let's say if the height of each children is fixed to 100 pixels then ListView should automatically adjust its height to 100 pixel but currently it doesn't. We have to wrap ListView inside some Fixed height widget like Container or Sizedbox etc.

CodePudding user response:

Usually, a ListView (as well as GridView, PageView, and CustomScrollView) tries to fill all the available space given by the parent element, even when the list items would require less space.

With shrinkWrap: true, you can change this behavior so that the ListView only occupies the space it needs (it will still scroll when there are more items).

Hope this helps. Happy Coding :)

CodePudding user response:

Let's say if the height of each children is fixed to 100 pixels

The problem is, you can't assume this. What if their height is different between the children? The horizontal ListView takes up all height possible for this reason. It can't know the height of all children beforehand. The reason it uses a builder is to be efficient and only call the builder for the children that are in view. What if all currently visible children are height 100, but suddenly the next one that scrolls into view is larger? If the ListView would have a height equal to the tallest child you can have very unwanted behavior of the height jumping around while scrolling.

  • Related