How to show empty state in listview while using shimmer in flutter

Issue

I have a list view and its fetching from api service. I need to show a shimmer till api response come and show listview if there is data form api and show an empty state message if no data. Please check my below code that what i have implemented. shimmer and list item view working perfectly but if the list is empty my empty state view not showing.. its shows as blank view.

productListWidget() {
return Expanded(
        child: ListView.builder(

            itemCount: isLoading? 5 : searchedProductList.length,
            padding: EdgeInsets.only(left: 8, right: 8, top: 8, bottom: 8),
            scrollDirection: Axis.vertical,
            shrinkWrap: true,
            itemBuilder: (context, index) {
              if(isLoading){
                return productItemShimmer();
              }else {
                print(isEmptyList);
                return isEmptyList?  pItemEmpty() :productItem(searchedUnitList[index], index) ;
              }
            },

            ));

Solution

searchedProductList.length returns 0 when list is empty. You can do

Expanded(
  child: ListView.builder(
    itemCount: isLoading
        ? 5
        : searchedProductList.isEmpty
            ? 1
            : searchedProductList.length,
    itemBuilder: (context, index) {
      if (isLoading) {
        return Text("shimmer widget hereF");
      } else {
        print(searchedProductList.length);
        return searchedProductList.isEmpty
            ? Text("Empty")
            : Text("product Item $index");
      }
    },
  ),

This will return single widget while list is empty.

Answered By – Yeasin Sheikh

Answer Checked By – Senaida (FlutterFixes Volunteer)

Leave a Reply

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