Reputation: 23
I am trying to fetch data from Firestore and display it in cards using ListView.builder
. I have a boolean isAvailable
with which I wish to reorganize the order of data. If it's true, it's placed at top of the list, if it's false, it's placed at the bottom of the list. So here's the partial code,
Assume I have a class User with the corresponding fields of Firebase. When I call that filter function and append the instances of User and run the program, the list is repeated about 12 times. However, if I don't filter the content and just use the ListView.builder
as it is, then it's displaying properly.
Assume userTile
returns a Card with the user content within it.
For some reason, the filter function is being called multiple times and the lists are therefore being appended multiple times as well. Is there any work around to this? I want to display the available content at the top and the notAvailable content at the bottom in that order.
I also tried using a counter and making sure filter won't run multiple times like so
int count = 0
and enclosing the for loop with if (count < users.length)
and adding count = count + 1
at the end.
However, that doesn't seem to solve the problem either.
I didn't call the userTile on notAvailable list because I want it to work with available list first.
List notAvailableData = [];
List availableData = [];
List orderedList = [];
void filterContent(List users) {
for (int i = 0; i < userData.length; i++) {
User userData = users[i];
if (userData.isAvailable == true) {
available.add(userData);
} else {
notAvailable.add(userData);
}
}
}
@override
Widget build(BuildContext context) {
final users = Provider.of<List<User>>(context) ?? [];
filterContent(users);
return ListView.builder(
itemCount: available.length,
itemBuilder: (context, index) {
return _userTile(context, available[index], index);
},
);
}
}
Upvotes: 2
Views: 1358
Reputation: 7941
There are dozen of ways to solve your problem and I will just show you a short way; just refresh your lists (available
, and notAvailable
) when your function starts;
void filterContent(List users) {
available = [];
notAvailable = [];
for (int i = 0; i < userData.length; i++) {
User userData = users[i];
if (userData.isAvailable == true) {
available.add(userData);
} else {
notAvailable.add(userData);
}
}
}
Upvotes: 1