The function finds only one element, even if there is more than one - flutter

The function below finds only one item in the list, even if there are multiple items, how do I fix this function to find all items?
List newList = [];
if (value.isNotEmpty) {
for (var element in pressures) {
if (element.pressure.contains(value) ||
element.date.toString().contains(value)) {
newList.clear();
newList.add(element);
}
}
items.value = newList;
} else {
items.value = pressures;
}

You are clearing the list on loop
if (value.isNotEmpty) {
newList.clear(); // you can clear it on top of the loop
for (var element in pressures) {
if (element.pressure.contains(value) ||
element.date.toString().contains(value)) {
// newList.clear(); //remove this
newList.add(element);
}
}
items.value = newList;
} else {
items.value = pressures;
}

Related

flutter search in search

This is the onsearch function that searches for all custnum addresses.
onSearch(String text) async {
print(text);
List<Item> itemII = items;
if (text.isNotEmpty) {
List<Item> itemList = [];
for (var item in itemII) {
if (item.custnum == text.toLowerCase().toUpperCase()) {
itemList.add(item);
}
}
setState(() {
searchText = text;
searchitems.clear();
searchitems.addAll(itemList);
MainPage.searchItemMainPage.addAll(itemList);
if (searchitems.isNotEmpty) {
print({MainPage.searchItemMainPage[0].address});
searchitems[0].address!.sort((a, b) {
if (a.for_bill == 'Y' && b.for_bill == 'N') {
return -1;
} else if (a.for_bill == 'N' && b.for_bill == 'Y') {
return 1;
} else if (a.for_ship == 'Y' && b.for_ship == 'N') {
return -1;
} else if (a.for_ship == 'N' && b.for_ship == 'Y') {
return 1;
} else if (a.for_contact == 'Y' && b.for_contact == 'N') {
return -1;
} else if (a.for_contact == 'N' && b.for_contact == 'Y') {
return 1;
} else {
return 0;
}
});
}
});
} else {
setState(() {
searchCus.clear();
searchitems.clear();
MainPage.searchItemMainPage.clear();
// searchitems.addAll(items);
print('searchitems : $searchitems');
});
}
}
This is the onsearchaddr function, it finds the address in searchitems after the search. By typing the name of the field addr, then the address will be displayed.
onSearchAddr(String text) {
List<Item> result = searchitems;
if (text.isNotEmpty) {
List<Item> itemList = [];
for (var item in result) {
item.address = item.address!
.where((element) =>
element.addr1!.toUpperCase().toLowerCase().contains(text))
.toList();
itemList.add(item);
}
setState(() {
searchitems.clear();
searchitems.addAll(itemList);
print('itemList : ${itemList}');
});
} else {
setState(() {
searchitems.clear();
searchitems.addAll(MainPage.searchItemMainPage);
print(
'SearchitemsMainPage : ${MainPage.searchItemMainPage[0].address}');
});
}
}
Could you please write some code to modify onsearchaddr, it can search as typed but when it clears text it doesn't show information of searchitems as before but it shows information of last typed message.
It's like the previous backup wasn't provided.

How to search for 2 different parameters in dart list?

How to search for 2 different parameters in a dart list?
Is there a simple method?
Can I solve the problem using contains?
void _runFilter(String searchKeyword) {
List<Product> results = [];
if (searchKeyword.isEmpty) {
results = allProducts;
} else {
results = allProducts.where(
(element) =>
element.name.toLowerCase().contains(searchKeyword.toLowerCase()) || element.image.toLowerCase().contains(searchKeyword.toLowerCase()),
),
)
.toList();
results = results +
allProducts
.where(
(element) => element.image.toLowerCase().contains(
searchKeyword.toLowerCase(),
),
)
.toList();
}
// refresh the UI
setState(() {
filteredProducts = results;
});
}
You can write all sorts of if-else-combinations in a closure. If you use the {} notation instead of => it will become clearer. Something like this will accomplish what you are looking for:
results = allProducts.where( (element) {
if ( element.name.toLowerCase().contains(searchKeyword.toLowerCase()) {
return true;
} else if ( element.image.toLowerCase().contains(searchKeyword.toLowerCase()) {
return true;
} else {
return false;
}
}).toList();
If this step is clear, you can then try to combine individual statements into a boolean combination via || or && if this looks more convenient in your code.

Listen to a new value of a bloc and generate a list of listened items

I have this StreamSubscription field called followSubscribtion. It listens if there is a new follower and then calls populateFollower to load follower profile.
followsSubscription =
getBloc(context).followsHandler.stream.listen((value) async {
if (value.status == Status.success) {
await populateFollows();
}
});
});
populateFollows() async{
if (getBloc(context).followsModel.length > 0) {
for (var i = 0; i < getBloc(context).followsModel.length; i++) {
getBloc(context).loadFollowsProfile(getBloc(context).followsModel[i].userId);
break;
}
}
}
This works fine, But I want each profile that will be loaded to be added to a list, How do I do that?
loadFollowsProfile method
loadFollowsProfile(int id , List<UserProfileModel> profileList) {
getFollowsProfileHandler.addNetworkTransformerStream(
Network.getInstance().getUserProfile(id), (_) {
userProfileModelBloc = UserProfileModel.fromJson(_);
profileList.add(userProfileModelBloc);
return userProfileModelBloc;
});
}
You can do this by setting up loadFollowsProfile() to return a UserProfileModel, adding that to a list in the for loop of populateFollows(), and then returning that list from populateFollows().
List<ProfileObject> populateFollows() async{
List<ProfileObject> profileList = [];
if (getBloc(context).followsModel.length > 0) {
for (var i = 0; i < getBloc(context).followsModel.length; i++){
profileList.add(getBloc(context).loadFollowsProfile(
getBloc(context).followsModel[i].userId
));
break;
}
}
return profileList;
}
followsSubscription =
getBloc(context).followsHandler.stream.listen((value) async {
if (value.status == Status.success) {
profileList = await populateFollows();
}
});
});

Dart non-async function return wait until for loop is complete

Here is my code
List<DocumentReference> getStacks(
List<DocumentReference> favoritePlayers,
List<DocumentReference> stacks,
) {
List<DocumentReference> newStacks = [];
for (var i = 0; i < stacks.length; i++) {
stacks[i].get().then((DocumentSnapshot stackSnapshot) {
if (stackSnapshot.exists) {
DocumentReference thisstack = stackSnapshot['player'];
for (var x = 0; x < favoritePlayers.length; x++) {
if (favoritePlayers[x] == thisstack) {
newStacks.add(stacks[i]);
}
}
}
});
if (stacks.length - 1 == i) {
return newStacks;
}
}
}
I do not have the option in the platform I am using to make the function async or Future, so I am trying to figure out a way to not return until both for loops are done. I have tried while loops and do while, but I guess I am missing something, this method is close, but it seems it still finishes before the inner loop does and wants to return nothing.
Any thoughts would be great.
In your code, the loop goes to the next operation without waiting for "stacks[i].get()" .
If the "stacks[i].get()" function is not a Future function, you can use it as follows.
List getStacks( List favoritePlayers, List stacks) {
List newStacks = [];
for (final stack in stacks) {
DocumentSnapshot stackSnapshot = stack.get();
//code
newStacks.add(stackSnapshot);
}
return newStacks;
}
If it is a future function, it should be like this;
Future<List> getStacks( List favoritePlayers, List stacks) async{
List newStacks = [];
for (final stack in stacks) {
DocumentSnapshot stackSnapshot = await stack.get();
//code
newStacks.add(stackSnapshot);
}
return newStacks;
}

Fixed List is not updating with for loop - Flutter

I've a fixed list reservedGuest. After checking the condition in for loop I want to update the seats if the membership date has expired. The list is not updating. The code is as follows. PS. The List is filled through API on init().
class MyClubController extends GetxController {
List goldLane = List.filled(3, null, growable: false);
void _alterLanesOnContractEnds() {
for (var i in goldLane) {
print("\n\n I: $i");
if (i == null ||
DateTime.parse(i['contractEnds']).isBefore(
DateTime.now(),
)) {
i = null;
print('Can be removed');
} else {
print('Cannot be removed');
}
}
update();
}
}
A for-in loop will not allow you to reassign elements of the List. When you do:
for (var i in goldLane) {
// ...
i = null;
}
you are reassigning what the local i variable refers to, not mutating the goldLane List.
You instead can iterate with an index:
void _alterLanesOnContractEnds() {
for (var i = 0; i < goldLane.length; i += 1) {
var element = goldLane[i];
print("\n\n I: $element");
if (element == null ||
DateTime.parse(element['contractEnds']).isBefore(
DateTime.now(),
)) {
goldLane[i] = null;
print('Can be removed');
} else {
print('Cannot be removed');
}
}
update();
}
You can just create a new List where unqualified guests are nullified. For example,
void _alterLanesOnContractEnds() {
goldLane = goldLane.map(
(guest) => guest == null || DateTime.parse(guest['contractEnds']).isBefore(DateTime.now()) ? null: guest
).toList(growable: false);
update();
}
You should not and cannot modify a list while iterating with its iterator.
Elaborated by Jamesdlin,
Modifying the elements of a List while iterating is fine. Modifying
the length of the List while iterating is not, but that won't be a
problem for a non-growable List.
The bottom line is you should not mutate the size of the list while iterating.
I solved it by using
goldLane.forEach(
(element) {
print('\n\n ELEMENT: $element');
if (element == null ||
DateTime.parse(element['contractEnds']).isBefore(
DateTime.now(),
)) {
int ix = goldLane.indexWhere(
(element) => element != null
? DateTime.parse(element['contractEnds']).isBefore(
DateTime.now(),
)
: true,
);
goldLane[ix] = null;
} else {
print('Cannot be removed');
}
},
);
Yet I'll test the other answers. Thank You.