Horizontal ListView.Builder() not working in Flutter

I have ListView as below in my flutter application:

widgetToReturn = ListView.builder(
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemBuilder: (context, innerIndex) {
          return Text("Test");
          
        },
        itemCount: widget.objEvent!.details![index].items!.length); 
})

It works perfectly fine with Vertical scroll direction.
But, When I am trying to make it Horizontal as below:

Using:

scrollDirection: Axis.horizontal,

As below:

widgetToReturn = ListView.builder(
        scrollDirection: Axis.horizontal,
        shrinkWrap: true,
        physics: NeverScrollableScrollPhysics(),
        itemBuilder: (context, innerIndex) {
          return Text("Test");
          
        },
        itemCount: widget.objEvent!.details![index].items!.length); 
})

Issue with Horizontal direction is that nothing displaying on screen and it gives me below error :

The following assertion was thrown during performLayout(): ‘package:flutter/src/rendering/viewport.dart’: Failed assertion: line
1874 pos 16: ‘constraints.hasBoundedHeight’: is not true.

Either the assertion indicates an error in the framework itself, or we
should provide substantially more information in this error message to
help you determine and fix the underlying cause. In either case,
please report this assertion by filing a bug on GitHub:
https://github.com/flutter/flutter/issues/new?template=2_bug.md

What I am doing wrong here?

>Solution :

You need to set height for listview if you want it horizontal, one thing you can do is wrap it with SizedBox and set its height:

SizedBox(
        height: 20,
        child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemBuilder: (context, innerIndex) {
              return Text("Test");
            },
            itemCount: widget.objEvent!.details![index].items!.length),
      ),

if you don’t want to set static height you can use row and SingleChildScrollView:

SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        child: Row(
          children: List<Widget>.generate(widget.objEvent!.details![index].items!.length, (index) => Text("Test")),
        ),
      )

Leave a Reply