Check if ListView is empty in flutter
Asked Answered
S

2

13

Is there a way to check if ListView is empty.

ListView.builder(
  itemCount: _items.length,
  itemBuilder: (context, index) {
    return _buildFilteredItem(context, index);
  },
)

I want to search through my items and if its empty show a Text widget saying no items found. _buildFilteredItem returns null if the item could not be found.

Sunshinesunspot answered 15/11, 2018 at 16:59 Comment(0)
S
43

Check _items before creating ListView

return _items.isEmpty ? Center(child: Text('Empty')) : ListView.builder(
  itemCount: _items.length,
  itemBuilder: (context, index) {
    return _buildFilteredItem(context, index);
  },
)
Spirillum answered 15/11, 2018 at 17:3 Comment(5)
what if the _items is null?Steere
If it can be null - you may change _items.isEmpty to (_items?.isEmpty ?? true)Spirillum
I can't use your above commented code, i have the same Listview.builder to check the list items are null or empty. more errors are pops up.Steere
locations == null ? Center(child: Text('Empty')) : ListView.builder() seems to be worksSteere
In you example you're checking only for null not for empty. And for empty list you'll get empty screen without placeholder. Could you describe what errors are popping up?Spirillum
H
-2

To check for empty list the you can do

ListView.builder(
   itemCount:_items.length, 
   builder:(context, index){ 
      _items.length==0
      ?return Center(child:Text("List is empty"))
      :return _buildFilteredItem(context, index);})
Hypoploid answered 18/6, 2022 at 11:32 Comment(1)
List builder won't build the widget at all if the item list is emptyValency

© 2022 - 2025 — McMap. All rights reserved.