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.

0

2 Answers 2

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);
  },
)
Sign up to request clarification or add additional context in comments.

5 Comments

what if the _items is null?
If it can be null - you may change _items.isEmpty to (_items?.isEmpty ?? true)
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.
locations == null ? Center(child: Text('Empty')) : ListView.builder() seems to be works
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?
-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);})

1 Comment

List builder won't build the widget at all if the item list is empty

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.