flutter list contains check model not working - flutter

// ----- a list to store the favourites courses list
List<FavouriteModel> _favCourses = [];
void initAddToFav(FavouriteModel model, BuildContext context) {
if (_favCourses.contains(model)) {
_courseController.removeFromFavourite(model);
AlertHelper.showSanckBar(
context, 'Remove from favourites !', AnimatedSnackBarType.error);
notifyListeners();
} else {
_courseController.addToFavourite(model);
AlertHelper.showSanckBar(
context, 'Added to favourites !', AnimatedSnackBarType.success);
notifyListeners();
}
}
When try check _favCourses.contains favourite model then if condition not working even data exsist else part working

You are using .contains on a list of FavouriteModel objects. Dart doesn't automatically know how to test if one object is equal to another in the same way that it compares numbers or strings. So it will compare the item by memory address. That is unless you tell it how to test if the two objects are equal using a key.
Take a look at this answer here which uses a different way of checking if the list contains the item.
Check whether a list contain an attribute of an object in dart

you are check wrong condition because you applied the condition on _favCourses list and perform the task in _courseController.
Correct your if condition
If(_courseController.contains(model))
{
_courseController.removeFromFavourite(model);
AlertHelper.showSanckBar(context, 'Remove from favourites !', AnimatedSnackBarType.error);
notifyListeners();
}

Related

Flutter iterate through Stream<List<DocumentSnapshot<Object?>>>

I have an object of type
Stream<List<DocumentSnapshot<Object?>>>
That is returned from my database. I'm using it in a method that sends data and such so I don't believe I can use a stream builder with it to iterate over it.
I want to be able to loop through each one and use an if statement so I can check data on each document snapshot in the list
I worked it out I sumply just had to do
users.listen((List<DocumentSnapshot> documentList) {
// doSomething()
documentList.forEach((DocumentSnapshot document) {
//do code in here
}
}

Why would you create a Copy of a List to check if the List contains an Element of the Copy?

Copied lists
I stumbled across the following snippet while browsing through the Flutter framework repo:
for (final ValueChanged<RawKeyEvent> listener in List<ValueChanged<RawKeyEvent>>.from(_listeners)) {
if (_listeners.contains(listener)) {
listener(event);
}
}
As far as I know, List.from should create a copy with the exact same elements as the original list, so they should have the same elements, I guess?
For context, the _listeners variable is declared and initialized like this:
final List<ValueChanged<RawKeyEvent>> _listeners = <ValueChanged<RawKeyEvent>>[];
Question rephrased
Basically, is there ever a way the if-condition would not be true?
Type cast in List.from
The author did not use List.of, so maybe List.from discards some elements when the types of the elements do not match?
But then, the _listeners variable already enforced the exact same type, so no element with non-matching types can be added anyway, right?
This is something that ChangeNotifier also does.
The reason for both the list clone and the contains call is to support having listeners add and remove listeners. Otherwise, there could be a ConcurrentModificationError.
For example:
ChangeNotifier notifier;
final listener = () => print('hey');
notifier.addListener(() {
if (something) {
notifier.removeListener(listener);
}
});

convert Stream<List<String>> to List<String> in flutter

I am trying to convert a Stream<List<String>> to List<String> in flutter
here is my code
Stream<List<String>> _currentEntries;
/// A stream of entries that should be displayed on the home screen.
Stream<List<String>> get categoryEntries => _currentEntries;
_currentEntries is getting populated with data from a database.
I want to convert _currentEntries into List<String>
I tried the following code but doesn't work:
List<List<String>> categoryList () async {
return await _currentEntries.toList();
}
I get the following error:
A value of type List<List<String>> can't be returned from method categoryList because it has a return type of List<List<String>>
Can someone help how to solve this issues and convert a Stream<List<String> to List<String>?
The issue seems to be with your return type for categoryList. You're returning as List of Lists when the Stream only contains a single layer of List. The return type should be Future<List<String>>.
Use .first, .last, or .single in addition to await to get just a single element, and toList() should be removed.
Future<List<String>> categoryList () async {
return await _currentEntries.first;
}
Also a quick tip: Dart automatically generates getters and setters for all fields so the getter method you show isn't necessary.
As title said, question is how to convert stream of some items to item. So what Christopher answered it is ok but only if you want to take the first value from the stream. As streams are asynchronous, they can provide you a value in any point of a time, you should handle all events from the stream (not only the first one).
Let's say you are watching on a stream from database. You will receive new values from database on each database data modification, and by that you can automatically update GUI according to newly received values. But not if you are taking just first value from stream, it will be updated only the first time.
You can take any value and handle it ("convert it") by using listen() method on a stream. Also you can check this nicely written tutorial on Medium. Cheers!
Stream<List<String>> _currentEntries = watchForSomeStream();
_currentEntries.listen((listOfStrings) {
// From this point you can use listOfStrings as List<String> object
// and do all other business logic you want
for (String myString in listOfStrings) {
print(myString);
}
});
I have no idea that Stream can await for the API call from the server, in my case I'm using BLOC pattern and using Future<List<String>> getCategoryList async () {...} and to get the List I going to use like this:
Future<List<String>> getCategory() async {
var result = await http.get();
//Some format and casting code for the String type here
return result;
}
Hope this help

Spring Batch - Invoke read() method in Reader multiple times

I am trying to implement calling read() method in the itemReader multiple times.
For Eg:
I have a list of POJO in which I will have one string variable with values either A or B or C.
I have to sort this list based on alphabetical order and segment it into three list for each value. i.e., list for value A and list for value B
and list for value C.
I need to send each list to the read() method in the itemReader one by one.
Once List for A is processed and write, then I need to send List for B and so on..
Is this doable? Any help is appreciated.
Although I am not very clear on what you are trying to achieve, I don't see any reason it cannot be done.
I assume you mean either of this:
1. You want the "item" to be process to be a whole list of POJO with same ABC Type, or
2. You want the item to be the POJO itself, and you want them to be processed in order of ABC Type
2 is straight-forward. At the first read, prepare all the POJOs, sort it. I assume they are in some kind of
In psuedo code, it looks like this
class MyReader implements ItemReader<MyPojo> {
private List<MyPojo> values;
MyPojo read() {
if (values == null) {
values = getPojos();
sort values;
}
if (values.isEmpty()){
return null;
} else {
return values.popFront();
}
}
}
1 is nothing more complicated. You will need to group POJOs with same ABC type in same list, and return the lists one by one. It can be easily done by using a TreeMap<String, List<MyPojo>>
In psuedo code, it looks like this
class MyReader implements ItemReader<List<MyPojo>> { // note the item is List<MyPojo>
private NavigableMap<String, List<MyPojo>> values;
List<MyPojo> read() {
if (values == null) {
values = new TreeMap<>();
pojos = getPojos();
for (pojo : pojos) {
if (values do not contain pojo.abcType() ) {
values.put(pojo.abcType(), new ArrayList(pojo));
} else {
values.get(pojo.abcType()).add(pojo);
}
}
}
if (values.isEmpty()){
return null;
} else {
return values.popFirstEntry().value();
}
}
}
If your list of items is fully available (you have a List<Pojo> loaded with all items) you can:
use a ListItemReader and inject into the ordered list
use a custom ItemReader and sort items after first ItemReader.read()
About break the best way is to use a custom CompletionPolicy based on pojo 'string variable'; in this manner your writer will receive a list where POJO's 'string variable' has the same values for all list items (check How to read csv lines chunked by id-column with Spring-Batch? for sample code).

GXT add filter to store

I'm having problems with a relatively simple piece of code.
I'm trying to set a filter for my store items (store associated with a GridView).
gridStore.addFilter(new StoreFilter<IncidentDto>() {
#Override
public boolean select(Store<IncidentDto> store, IncidentDto parent, IncidentDto item) {
if (item.getDescription().equals("WEEEE-TEST")) {
return true;
} else {
return false;
}
}
});
The problem is the store doesn't filter at all.
Thanks to anyone who will take the time to help me out with this.
Don't forget to enable the filters - this exists so that you can make several filter modifications without actually asking them to act:
gridStore.setEnableFilters(true);
Sorting doesn't have this as there isn't a concept of turning sorting 'off' - items are sorted to have a new order, then they stay that order. In contrast, filters can be turned back off to restore the items that are no longer visible.
If you trace the code, you will notice that the filter is not called in onLoad(). You have to manually call filter();