I have the following code
List toCheck = ['province','regency','district','village'];
List data = [];
toCheck.forEach((value) {
//sample data would looke like (object.province)
if(object.value!=null){ => need to call with object.value
data.add(value);
}
});
If it is in php, that would be look like ${$value}
Try this:
ElevatedButton(onPressed: (){
List toCheck = ['province','regency','district','village'];
List data = [];
toCheck.forEach((value) {
//sample data would looke like (object.province)
if(value!=null){
data.add(value);
}
});
If I understand what you want correctly, this should check if the values of your list are not null, and if so, it will add each value to the data list.
Related
This code sample works fine.
var box = await Hive.openBox<MainWords>('mainWords');
box.values.where((item) {
return item.category == "6" || item.category == '13';
}).toList();
I am trying to filter a list with whereIn condition but it must filter like
List<String> categoryList = ['6', '13'];
var box = await Hive.openBox<MainWords>('mainWords');
box.values.where((item) {
return item in categoryList; // just an examle
}).toList();
How can i achive this?
You should not use the keyword in but the method contains to check if your item exists inside categoryList. Moreover you cannot compare values of different types, I'm seeing that you are returning with box.values an Iterable<MainWords>.
I don't know the content of this class but the item variable is of type MainWords and so it cannot be compared with a String object directly.
I am supposing that you have some access to a String value from your class MainWords so you will need to compare this value with your list.
Code Sample
List<String> categoryList = ['6', '13'];
var box = await Hive.openBox<MainWords>('mainWords');
// As I don't know what are MainWords' properties I named it stringValue.
box.values.where((item) => categoryList.contains(item.stringValue)).toList();
I have a function which creates a sublist from a large(very large list). After creating this list, the function goes on treating it (deleting duplicates, sorting...).
As long as the list was not too big, it worked fine. But now, I get "The Getter length was called on null". I suppose, it's because the second part of the function (after the loop) starts before the sublist is completed... so it doesn't work...
How can we force the function to wait for the loop to be over to continue the rest of the treatment ?
Is it with Async /Await ? Or can we do something like "While... something is not over...", or "As soon as something is done... do that" ? (My suggestions might be naive, but I am a beginner...)
Here is the code :
List themeBankFr() {
List<Map> themeBankFr = [];
for (Word word in wordBank) {
for (Thematique wordTheme in word.theme) {
themeBankFr.add({
'themeFr': wordTheme.themeFr,
'image': wordTheme.image,
});
}
}
// convert each item to a string by using JSON encoding
final jsonList = themeBankFr.map((item) => jsonEncode(item)).toList();
// using toSet - toList strategy
final uniqueJsonList = jsonList.toSet().toList();
// convert each item back to the original form using JSON decoding
final result = uniqueJsonList.map((item) => jsonDecode(item)).toList();
// sort the list of map in alphabetical order
result.sort((m1, m2) {
var r = m1['themeFr'].compareTo(m2['themeFr']);
if (r != 0) return r;
return m1['image'].compareTo(m2['image']);
});
return result;
}
i think i have a good answer that may helps you and it will as following
first create another function to do the work of for loops and this function returns a future of list that you need like below
Future<List<Map>> futureList(List wordBank){
List<Map> themeBankFr = [];
for (Word word in wordBank) {
for (Thematique wordTheme in word.theme) {
themeBankFr.add({
'themeFr': wordTheme.themeFr,
'image': wordTheme.image,
});
}
}
return Future.value(themeBankFr);
}
after that you can use this function inside your code and use it as async await and now you will never run the below lines before you return this array like below
List themeBankFr() async {
List<Map> themeBankFr = await futureList(wordBank);
// convert each item to a string by using JSON encoding
final jsonList = themeBankFr.map((item) => jsonEncode(item)).toList();
// using toSet - toList strategy
final uniqueJsonList = jsonList.toSet().toList();
// convert each item back to the original form using JSON decoding
final result = uniqueJsonList.map((item) => jsonDecode(item)).toList();
// sort the list of map in alphabetical order
result.sort((m1, m2) {
var r = m1['themeFr'].compareTo(m2['themeFr']);
if (r != 0) return r;
return m1['image'].compareTo(m2['image']);
});
return result;
}
i think this will solve your problem and i hope this useful for you
Hello everyone i am trying to update a map value inside of a list if the value already exists then it should just update the quantity. The problem is that the code only works for the first entry and does not work for the rest of them.
here is my code.
for (var map in items) {
print(countItem.indexOf(_productIndex));
if (map['\'id\''] == '\'$_productIndex\'') {
var toRemove = countItem.indexOf(_productIndex);
items.removeAt(toRemove);
items.add({
'\'totalQuantity\'': count,
'\'type\'': '\'unit\'',
'\'id\'': '\'$_productIndex\'',
'\'price\'': count * int.parse(_productPrice),
'\'name\'': '\'$_productName\'',
});
} else {
items.add({
'\'totalQuantity\'': count,
'\'type\'': '\'unit\'',
'\'id\'': '\'$_productIndex\'',
'\'price\'': int.parse(_productPrice),
'\'name\'': '\'$_productName\'',
});
}
break;
}
Your using indexOf for the wrong variable. Change it from _productIndex to map.
for (var map in items) {
print(countItem.indexOf(map));
...
I have a map returned from json.decode of type Map<String,dynamic>
The dynamic part contains another map which I want to have in a separate variable. I managed to do that in the following way:
Map<DateTime, List<DayOffDto>> mapToReturn = Map();
Map<String, dynamic> responseBody = json.decode(
response.body,
reviver: _reviver,
);
if (responseBody == null) {
throw NoDataServerException();
}
responseBody.entries.forEach((element) {
Map map = element.value;
//map.values;
map.entries.forEach((element2) {
mapToReturn[element2.key] = element2.value;
});
});
//mapToReturn contains now the extracted map from responseBody
and the reviver function just does some converting for me
_reviver(dynamic key, dynamic value) {
if (key != null && value is Map && (key as String).contains("-")) {
var object = value;
final DayOffDto dayOffDto = DayOffDto.fromFirebase(
key_firebase: key as String,
parsedJson: value,
rota: rotaParam,
chosenYear: yearParam);
DateTime datetime = Helper.getDateTimeFromDayNumber(
dayOffDto.dayNumber,
dayOffDto.year,
);
Map<DateTime, List<DayOffDto>> internalMap = LinkedHashMap();
internalMap[datetime] = [dayOffDto];
return internalMap;
}
return value;}
I do not think it is the best way of extracting . Any idea for the optimized code?
responseBody.values returns Iterable<V>
so when I do
mapToReturn = responseBody.values i am getting an error
Working with Map can be hard sometimes. I would like to tell you that there is something as easy as mapToReturn = responseBody.values, but as of today, there is not (that I could find).
However, I can give you one small block of code that does the same as your first code block.
As you are not using the keys of your first map, instead of responseBody.entries you should use responseBody.values. So the code block would end up like this:
responseBody.values.forEach((value) {
return value is Map<DateTime, List<DayOffDto>>
? mapToReturn.addAll(value)
: null;
});
And if you are completely sure about the value Type (you should, as you are using a reviver) you can make it only one line of code.
responseBody.values.forEach((value) => mapToReturn.addAll(value));
I hope this can help you!
I am creating an app using flutter and dart.
I have a list of objects with the name parameter, and I want to check if the user input is equal to any of the names of objects inside list.
Simply
I want to take input from a user and switch if one of the objects inside a list has this value to add it in a list
I have searched a lot but with nothing.
void main() {
Data data = Data();
String name = 'Messi';
//I want to switch if name equals any name inside players list without index
}
class Data {
List<Player> players = [
Player(
name: 'Messi',
),
Player(
name: 'Mohamed',
),
];
}
If you want to get a filtered list from the list you have, you can do this:
players.where((player) => player.name == userInput).toList();
If you just want the first occurrence, you can do this:
players.firstWhere((player) => player.name == userInput);
You can use the method forEach from the lists.
It basically works like this:
players.forEach ((player) {
if(player.name == name){
your code...
}
});
Hope this helps!