how to using where expression on a list item property that is a list of string at dart - flutter

I need a way to search on a list item (list of string) in a list of object. something as below
filtered = allExhibitors.where((element) => element.product_categories == element.product_categories?.where((element2) => element2 == filterModel.categoryId)).toList(growable: true);
allExhibitors is a list of exhibitors (List<Exhibitor>) and product_categories is list of string (List<String>)
Thank you in advance.

You can use contains.
Something like:
class Exhibitor {
List<String> product_categories = [];
}
void f() {
var allExhibitors = <Exhibitor>[];
var filterModelId = '';
var filtered = allExhibitors
.where((element) => element.product_categories.contains(filterModelId))
.toList(growable: true);
}

Related

How to fix mapIndexed function in flutter?

I have a function that map from one list and add every item to another list:
List<TimeSeriesValues> list = (data["list"] as List).mapIndexed(
(index, e) => TimeSeriesValues(DateTime.tryParse(e["detectedAt"])!,int.parse(e['score']))).toList();
This is TimeSeriesValues class:
class TimeSeriesValues {
final DateTime time;
final int values;
TimeSeriesValues(this.time, this.values);
}
And I want to add if statements, like if e['score'] != 0 then we add the item to the list otherwise not.
If e['score'] != 0 then add TimeSeriesValues(DateTime.tryParse(e["detectedAt"])!, int.parse(e['score'])) to list else not
This is the response from Api:
[{detectedAt: 2022-11-28T00:00:00.000Z, score: 57},...] // data['list']
Try this:
List<TimeSeriesValues> list = (data["list"] as List).mapIndexed(
(index, e) => TimeSeriesValues(DateTime.tryParse(e["detectedAt"])!,int.parse(e['score']))).toList();
List<TimeSeriesValues> filteredList = list.where((e) => e.values != 0).toList();
Simply use for each loop as following
List<TimeSeriesValues> list = [];
(data["list"] as List).forEach((e){
if(int.parse(e['score']) != 0){ list.add(TimeSeriesValues(DateTime.tryParse(e["detectedAt"])!,int.parse(e['score'].toString()))); }
});

Group and sort map in a predefined order

Here is an extension to group my tasks
/// EXTENSION
Map<K, List<T>> groupBy<T, K>(K key(T e)) {
Map<K, List<T>> map = {};
for (final element in this) {
var list = map.putIfAbsent(key(element as T), () => []);
list.add(element);
}
return map;
}
/// CODE
final List<String> requiredPrioritySortOrder = ['df','sc','de','dd'];
final Map<String, List<Task>> tasksByPriority = _selectedTasks.groupBy<Task, String>((e) => e.priority);
As a result, I have received a map but the sort order change every time after the task update.
How to sort tasksByPriority Map by key in a predefined order (requiredPrioritySortOrder).
Thanks :)
I am already find a solution but maybe there is another way?
_selectedTasks.groupBy<Task, String>((e) => e.priority, order:['sc','df']);
Map<K, List<T>> groupBy<T, K>(K key(T e), {Iterable order = const []}) {
Map<K, List<T>> mapped = {};
Map<K, List<T>> sorted = {};
for (final e in this) {
List list = mapped.putIfAbsent(key(e as T), () => []);
list.add(e);
}
if (order.isNotEmpty) {
order.forEach((e) {
if (mapped[e] != null) {
sorted[e] = mapped[e]!;
}
});
return sorted;
}
return mapped;
}

Comparing list with another list items and returning it if it has similar items

class Object1 {
final String id;
List<Object1list> lists = [];
Object1({this.id, this.lists});
class Object1list {
final String id;
final String item;
Object1list({this.id});
}
List<String> searchlist = ['object1','object2','object3'];
What i want to do is I want to search "object1list" items for "any" matches with "searchlist" items and
return it as contain function but I don't know how, something like:
return ???.contains(???)
Can somebody help me?
The below function will help you to get matched items:
bool doSearch(List<String> searchlist, List<String> lists) {
List<String> matched = [];
for (String s in searchlist) {
if (lists.contains(s)) {
matched.add(s);
}
//else {
// return false; // Uncomment these lines if you want "lists" to contain all searched items
//}
}
return matched.length > 0; // This for 0 or more items matched
}
Other ways:
import 'package:enumerable/enumerable.dart';
void main() {
final result1 = searchlist.isNotEmpty
? searchlist.distinct().length == searchlist.length
: false;
print(result1);
// OR
final result2 = searchlist.isNotEmpty
? searchlist.toSet().length == searchlist.length
: false;
print(result2);
}
List<String> searchlist = ['object1', 'object2', 'object3', 'object2'];

Boolean map in flutter

I have boolean position map for example
var position={"isAdmin":true,"isisPleb":false}
I wanna add all true position another list. how can I do this.
You can do this with basic for loop.
List<String> getPosition(Map newMap) {
List<String> positions = [];
for (var i in newMap.entries) {
if (i.value) {
positions.add(i.key);
}
}
return positions;
}
There is also simple way:
List listPosition = [];
position.forEach((key, value) {
if(value==true) listPosition.add(key);
});

How to do forEach in flutter

I am new in flutter. I want to do for each to check my array JSON. I know typescript is doing like this:
Object.keys(res).forEach(key => {
if (res[key].name === 'Max') {
match = true;
}
});
if (match) {
console.log ('Username has been taken');
} else {
console.log('Username is available');
}
My question is for dart language in Flutter, how to do that?
Please find the below sample code for forEach in dart, which can used in flutter also.
main() {
List<String> list = new List<String>();
list.add('apple');
list.add('ball');
list.add('cat');
list.forEach((element) => print(element));
Set<String> set = Set.from(list);
set.forEach((element) => print(element));
}
try this
var decodedData= json.decode(response.body);
for (var item in decodedDat){
if(item['name'] == 'Max'){
// if true
}
}
The Darty way to test whether an Iterable (and by extension List) contains an element that matches a predicate is with any.
bool match = list.any((s) => s == 'Max');