rameez khan
rameez khan

Reputation: 359

Flutter show only less 6 length on list view builder

I have a simple listview builder what I want is just show 6 values or less then 6.

This is my code

          Container(
            height: MediaQuery.of(context).size.height * 0.35,
              child: ListView.builder(
            shrinkWrap: true,
            scrollDirection: Axis.horizontal,
            itemCount: items['Items'].length,
            itemBuilder: (context, index) {
              var product = items['Items'][index];
              return FadeInAnimation(
                index,
                child: Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: 10.0),                      child: ProductCard2(
                    product: product,
                    isHorizontalList: false,
                  )
                ),
              );
            },
          ))

What I need to is itemCount: items['Items'].length less than 6. It has some time 2 length some time 10. What I need to is fix it to 6. So it will not show more than 6. But if have less than 6 so it will show.

If I fix 6 I itemCount then those items who have less than 6 then its showing error in UI.

Upvotes: 0

Views: 2197

Answers (2)

Nagual
Nagual

Reputation: 2088

try to add single line that will clamp length

      Container(
        height: MediaQuery.of(context).size.height * 0.35,
          child: ListView.builder(
        shrinkWrap: true,
        scrollDirection: Axis.horizontal,
        itemCount: items['Items'].length.clamp(0, 6), // this one
        itemBuilder: (context, index) {
          var product = items['Items'][index];
          return FadeInAnimation(
            index,
            child: Padding(
                padding: const EdgeInsets.symmetric(
                    horizontal: 10.0),                      child: ProductCard2(
                product: product,
                isHorizontalList: false,
              )
            ),
          );
        },
      ))

Upvotes: 1

leb1755
leb1755

Reputation: 1424

You can clamp the length property between a min and a max value (here, 0 and 6 respectively) :

itemCount : items['Items'].length.clamp(0,6)

This way, it will show only first 6 items max (or less if there are less).

Upvotes: 0

Related Questions