Boolean map in flutter - 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);
});

Related

How to combine a list of services from different array elements into one list in flutter

I have an array of data .
Here is a photo of the model:
This model has an array of services.
I want to use a request to combine all services from all elements and have one list.
I tried to do like this but it doesn't work. Maybe someone knows how to do it??
My example :
List<PriceServicesModel> get selectedServices {
List<PriceServicesModel> list = [];
for (var element in multiServicesModel) {
for (var services in element.services) {
list = [...list, services];
print(list);
}
return list;
}
return list;
}
I will be grateful for any help.
You should return the list at the end of function.
List<PriceServicesModel> get selectedServices {
final List<PriceServicesModel> list = [];
for (var element in multiServicesModel) {
list = list.addAll(element.services);
//return list; //This line should be removed
}
return list;
}
I made some optimisations here.
You don't need to create a list with every iteration, just use list.add() instead. And also remove the first return, so it doesn't return after the first loop.
List<PriceServicesModel> get selectedServices {
List<PriceServicesModel> list = [];
for (var element in multiServicesModel) {
for (var services in element.services) {
list.add(services);
}
}
return list;
}

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

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

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