I want to print the index of array element as another array. I have array list name btns. It contains the value is true or false. I want the index of element having true. here my code is
List<bool> btn = [true, false, true, false, false, false, false];
Map<int, bool> map2 = btn.asMap();
var arr = new List<int>();
map2.forEach((key, value) {
if (value) {
print(key);
arr.add(key);
}
});
print(arr);
It is printin [0,2]. And showing correct results. But when I put in method. It showing error.
List<int> getbtnsInArray() {
Map<int, bool> map2 = btn.asMap();
var arr = new List<int>();
map2.forEach((key, value) {
if (value) {
print(key);
arr.add(key);
}
});
return arr;
}
print (getbtnsInArray);
It showing the error is Closure: () => List from Function 'getbtnsInArray':.
I don't know the reason. Please help me to find the answer.
You need to add brackets to call the method.
print(getbtnsInArray());
Related
Error: "NoSuchMethodError: 'length' method not found. Receiver: null" when updating map values
List<ImageDetails> _images = [
ImageDetails(
imagePath: 'assets/images/meal1.jpg',
date: '2021-11-30',
details:
'',
),
ImageDetails(
imagePath: 'assets/images/meal2.jpg',
date: '2021-11-30',
details:
'',
),
];
var dateToImages = new Map();
_images.sort((a,b) => a.date.compareTo(b.date));
//group images by date
for (int i = 0; i < _images.length; i++) {
var d = _images[i].date; //convert string to Datetime
print("printing datetime in for loop");
print(d);
if (dateToImages.containsKey(d)) {
print("second element");
var list = dateToImages[d].add(_images[i]);
dateToImages[d] = list;
} else {
print("first element");
dateToImages[d] = [_images[i]];
}
}
var sortedKeys = dateToImages.keys.toList()..sort((a, b) => a.compareTo(b));
List<Widget> children = [];
print("=====printing datetoImages");
print(dateToImages);
print("======== printing sortedKeys");
print(sortedKeys);
int len = dateToImages['2021-11-30'].length;
Below is result of running above code
printing datetime in for loop
2021-11-30
first element
printing datetime in for loop
2021-11-30
second element
=====printing datetoImages
{2021-11-30: null}
======== printing sortedKeys
[2021-11-30]
After printing some variables, it seems like the issue is with the value for key "2021-11-30" in dateToImages being null... I don't understand why I keep getting null since it seems like the map building process in the for loop seems to be going well? Can anyone shed some light on this bug?
Thanks!
The error message suggests you are accessing length method which is not available.
since null doesn't have length method but list have it.
So, you may have a logical error, where you think you are returning list but the code is returning null
In your case:
Your Code is fine except for this part:
if (dateToImages.containsKey(d)) {
print("second element");
var list = dateToImages[d].add(_images[i]);
dateToImages[d] = list;
}
add() method returns void which will return null to var list and null will be sent to the map
Update it directly, replace above code with this:
if (dateToImages.containsKey(d)) {
print("second element");
dateToImages[d].add(_images[i]);
}
try this :
List<ImageDetails> _images = [
ImageDetails(
imagePath: 'assets/images/meal1.jpg',
date: '2021-12-30',
details:
'',
),
ImageDetails(
imagePath: 'assets/images/meal2.jpg',
date: '2021-11-30',
details:
'',
),
];
var dateToImages = new Map();
_images.forEach((img){
if(dateToImages.containsKey(img.date)){
dateToImages[img.date].add(img);
}else{
dateToImages[img.date] = [img];
}
});
var sortedKeys = dateToImages.keys.toList()..sort((a, b) =>
a.compareTo(b));
print("=====printing datetoImages");
print(dateToImages);
print("======== printing sortedKeys");
print(sortedKeys);
int len = dateToImages['2021-11-30'].length;
Output:
=====printing datetoImages
{2021-12-30: [Instance of 'ImageDetails'], 2021-11-30: [Instance of
'ImageDetails']}
======== printing sortedKeys
[2021-11-30, 2021-12-30]
I have and empty map, Map optionSelection = {};
And on every button click I want to add list of K,V pair map to optionSelection map.
Format in which I want to add Map.
{
"quiz_id": selectedOption,
"ques_id": questionId,
"user_ans_id": selectedOption,
}
In above Key and Value pair, in "ques_id": questionId -> questionId will be unique, So I want to check if the value already exist, if YES then I want to update the "user_ans_id": selectedOption value or else I want to add new list of K,V pair.
Below is the code I tried
final quesExist = optionSelection.containsValue(questionId);
if (quesExist) {
optionSelection.putIfAbsent(
"ques_id",
() => optionSelection.addAll(
{
"quiz_id": selectedOption,
"ques_id": questionId,
"user_ans_id": selectedOption,
},
),
);
} else {
optionSelection.addAll(
{
"quiz_id": selectedOption,
"ques_id": questionId,
"user_ans_id": selectedOption,
},
);
}
Hope I was able to explain my issue, Thank you in advance.
after a week of struggle and many tweaks in code, here is the final solution for above query.
// Declared empty List<Map>
List<Map> optionSelection = [];
// Variable to store bool value, if the question id exist
var questionExist;
// Feed the map in below form
Map<String, dynamic> userSelection = {
"quiz_id": widget.quizId,
"ques_id": questionId,
"user_ans_id": selectedOption,
};
// Check if the Ques Id Exist in List<Map> optionSelection
questionExist = optionSelection.any((map) => map.containsValue(questionId));
// Check using if else condition, if Ques Id exist, then run the forLoop,
// to iterate in List<Map>, else add a new Set of Map to the List<Map>
if (questionExist == true) {
print("If triggered");
for (var map in optionSelection) {
if (map.containsValue(questionId)) {
map.update("user_ans_id", (dynamic val) => selectedOption);
}
}
} else {
print("Else triggered");
optionSelection.add(userSelection);
}
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);
});
I've got list of strings named list and list of map named type
list ['value1', 'value2']
type [{data: 'value1', isSelected: false},{data: 'value5', isSelected: false}]
I want to update isSelected value in 'type' list if value in list is equal to type.data value
I managed to do it this way
if (type != null) {
for (var l in list) {
for (var t in type) {
if (l.data == t) {
l.isSelected = true;
}
}
}
}
Is there a more decent way of doing it?
You can use for with contains and when data is found no need to continue further. Hence, break the loop.
var list = ['value1', 'value2'];
var type = [{data: 'value3', isSelected: false}, {data: 'value4', isSelected:false}]
Edit
for (object in type) {
if (list.contains(object['data'])) { // changed from indexOf as recommended in comments
object['isSelected'] = true;
break:
}
});
If you just need to know if the value of data is contained in the list array, you only need 1 loop:
var list = ['value1', 'value2'];
var type = [{data: 'value3', isSelected: false}, {data: 'value4', isSelected:false}]
for (t in type) {
if (list.contains(t.data)) { // changed from indexOf as recommended in comments
t.isSelected = true;
}
}
How can I initialize a list inside a map?
Map<String,Map<int,List<String>>> myMapList = Map();
I get an error :
The method '[]' was called on null.
I/flutter (16433): Receiver: null
I/flutter (16433): Tried calling: [](9)
By just adding the elements when you create the map, or later by adding them. For example:
var myMapList = <String, Map<int, List<String>>>{
'someKey': <int, List<String>>{
0: <String>['foo', 'bar'],
},
};
or
var m2 = <String, Map<int, List<String>>>{}; // empty map
m2['otherKey'] = <int, List<String>>{}; // add an empty map at the top level
m2['otherKey'][2] = <String>[]; // and an empty list to that map
m2['otherKey'][2].add('baz'); // and a value to that list
print(m2);
prints {otherKey: {2: [baz]}}
Try initializing using {}
Map<String,Map<int,List<String>>> myMapList = {}; // just add {}
it will create an empty map and works perfectly fine.
In case for list of int as value
void main() {
List<int> dividends = [99,101,176,182];
Map map = new Map<int, List<int>>();
dividends.forEach((i) {
if(i > 0) {
map[i] = <int>[];
for(int j=1; j <= i;j++) {
if(i%j == 0) {
map[i].add(j);
}
}
// print('$i, $map[$i]');
}
});
print(map);
}