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

769 views Asked by At

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) ;
              }
            },

            ));
2

There are 2 answers

0
Md. Yeasin Sheikh On BEST ANSWER

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.

0
Kantine On

If your list is empty, the ListView builder won't build any children. You should move your empty test out of the list builder:

return Expanded(
        child: isEmptyList ? pItemEmpty() : 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 {
                return productItem(searchedUnitList[index], index) ;
              }
            },

            ));

Moreover, to display different widgets depending on the state of an operation, I would recommend to use FutureBuilder: https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html