How to fix mapIndexed function in flutter? - 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()))); }
});

Related

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

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);
}

How remove element duplicates in a list flutter

I am streaming api. With the API, I get 1 item each and add to the list. The fact is that the api stream works in a circle, and duplicates are added to the list. How can I eliminate duplicates?
Code add list:
groupData.map((dynamic item) => GetOrder.fromJson(item))
.where((element) {
if (element.orderId != null) {
if (!list.contains(element)) {
list.add(element);
}
return true;
} else {
return false;
}
}).toList();
If elements are primitives, you can use a Set:
final myList = ['a', 'b', 'a'];
Set.from(myList).toList(); // == ['a', 'b']
but if elements are objects, a Set wouldn't work because every object is different from the others (unless you implement == and hashCode, but that goes beyond this answer)
class TestClass {
final String id;
TestClass(this.id);
}
...
final myClassList = [TestClass('a'), TestClass('b'), TestClass('a')];
Set.from(myClassList).toList(); // doesn't work! All classes are different
you should filter them, for example creating a map and getting its values:
class TestClass {
final String id;
TestClass(this.id);
}
...
final myClassList = [TestClass('a'), TestClass('b'), TestClass('a')];
final filteredClassList = myClassList
.fold<Map<String, TestClass>>({}, (map, c) {
map.putIfAbsent(c.id, () => c);
return map;
})
.values
.toList();
That said, this should work for you
groupData
.map((dynamic item) => GetOrder.fromJson(item))
.fold<Map<String, GetOrder>>({}, (map, element) {
map.putIfAbsent(element.orderId, () => element);
return map;
})
.values
.toList();
You can use Set instead
A Set is an unordered List without duplicates
If this is not working, then chances are that u have different object for the same actual object. (meaning, you have in 2 different places in memory)
In this case .contains or Set will not work

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');