Dart/Flutter How to initialize a List inside a Map? - flutter

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

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

Why is the value in this map NULL?

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]

How can I use firstWhereOrNull with a map in Flutter?

How can I use firstWhereOrNull with maps in Flutter?
In other words, how can I do this:
final myVariable1 = myList.firstWhereOrNull(
(myVariable2) =>
!myList.containsValue(myVariable2));
Instead of using a list (myList), I'd like to do the same with a map (Map<String,int>).
Map<String,int> myMap = {};
myMap("stuff1") = 1;
myMap("stuff2") = 2;
myMap("stuff3") = 3;
Thanks
There is no such firstWhereOrNull method for Maps, but you can easily come up with one using extension methods:
extension ExtendedMap on Map {
/// The first entry satisfying test, or null if there are none.
MapEntry? firstWhereOrNull(bool Function(MapEntry entry) test) {
for (var entry in this.entries) {
if (test(entry)) return entry;
}
return null;
}
}
Here is how you can use it:
final map = <String, int>{
'stuff1': 1,
'stuff2': 2,
'stuff3': 3,
};
final test = map.firstWhereOrNull((entry) => entry.value == 2);
print(test); // Prints MapEntry(stuff2: 2)
final nullTest = map.firstWhereOrNull((entry) => entry.key == "stuff5");
print(nullTest); // Prints null
So, I created this implementation, I don't think it's the most optimized, also because it was necessary to use the cast since because of the sound null safety, it's not possible to return any value. But it works for you.
var myMap = {"key1": "value", "key2": 3};
var result = myMap.entries
.cast<dynamic>()
.firstWhere((e) => e.key == "key", orElse: () => null);
print(result);
I hope this helps in some way!

Flutter nullsafety: conditional List position

If I am not sure a list is null or not, I could do
final something = myList?[0].property;
What if I knew myList existed but was not sure there is an element in it?
Do I need to manually check that isNotEmpty?
final something = myList[0]?.property;
says The receiver can't be null, so the null-aware operator '?.' is unnecessary.
You need to define your list to be nullable.
e.g.:
List<myObject?> myList = [myObject(), null, null, myObject()]
// then error is not shown
final something = myList[0]?.property;
Example
void main() {
List<int?> list = null;
for (var i = 0; i< list.length; i++ ) {
print(list[i]?.isEven);
}
// Error: The value 'null' can't be assigned to a variable of type 'List<int?>' because
// 'List<int?>' is not nullable.
// - 'List' is from 'dart:core'.
// List<int?> list = null;
List<int?> list2 = [null, 2, 1, 3, null];
for (var i = 0; i< list2.length; i++ ) {
print(list2[i]?.isEven);
}
// no error
List<int?> list3 = [];
print(list3[5]?.isEven);
//no error
}
Yes. you need to check it is empty or not.
if myList exist and not null
late List<dynamic> myList;
myList = [];
if (myList.length > 0){
}
if myList can be null
late List<dynamic>? myList;
if (myList != null && myList!.length > 0) {
}

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