How to remove items from a list (Dart) | Firebase rtdb

Issue

I have a list that stores items that I don’t want to display as part of my StreamBuilder, ListView. This list retrieves its information from a firebase rtdb.

I use a StreamBuilder to populate the ListView, and then I use a for-loop to try and iterate through the list that contains items I don’t want to display. So far I can get the ListView populated, but the items removed from the StreamBuilder aren’t accurate.

Below is how I have approached it (Any help is much appreciated):

I can confirm that the list definitely contains the info I don’t want displayed

ListView.builder(
    physics: BouncingScrollPhysics(),
    itemCount: friends.length,
    itemBuilder: (context, index) {
      final friend = friends[index];

      if (friend.userID == uid){
        return null;
      } else {

        for (FriendSuggestionModel hidden in hiddenSuggestions){
          if (hidden.userID == friend.userID){
            return null;
          } else {
            return friendThumbnail(index, friend);
          }
        }
        return null;
      }
    });

Solution

First, I believe you need to return a Widget in itemBuilder, so don’t use return null instead you can return an empty container with return Container().

You also could use list.contains(x) method to verify if this id should be hide (as I imagine , as follows:

itemBuilder: (context, index) {
      final friend = friends[index];

      if (friend.userID == uid){
        return const Container();
      } else {
        return hiddenSuggestions.map((hidden) => hidden.userID).toList().contains(friend.userID)
          ? const Container()
          : friendThumbnail(index, friend);
      }
    }

Check that method docs here: https://api.dart.dev/stable/2.0.0/dart-core/Iterable/contains.html

Answered By – Leonardo Ugiete

Answer Checked By – Robin (FlutterFixes Admin)

Leave a Reply

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