How to get the length for each list according to its key inside map - flutter

how to get the length for each list according to its key
Map mymap= <String, List>;
Example
key1 : 5(length of the value(list))
key2 : 48

It seems similar to this,
you can do mymap['k1']?.length, here ?. means it will return null if there is no value.
Rest you can follow #zabaykal's answer.
Map<String, List> mymap = {
"k1": [1, 2, 4],
"k2": [5, 6, 7],
"k3": []
};
print(mymap['k1']?.length);
mymap.forEach((key, value) {
print('$key: ${value.length}');
});

If you want to create a second map with the original keys and the respective lengths as the value you can use the following code where initialMap is the original map with List<T> as values:
final mapListCount = initialMap.map((key, value) => MapEntry(key, value?.length));

Related

How to add a new value to Map in Dart?

this is my first post to StackOverflow.
I have been struggling with the Map data.
It’s been taking too much time to find a way more than I thought...
Ex)
Map<String, int> someMap = {
"a": 1,
"b": 2,
"c": 3,
};
How can I add a new value to the same key Map?
like this.
a:1, b:2, c:3,4,5,6etc....
I'd be grateful if you could tell me the correct way.
Thank you.
If you want multiple values for the same key, you'll need to change the value type: Right now it's int, but that can only be a single int, and by definition, a key only occurs once in a map.
If you change the type of the value to List<int>, you can add multiple values for the same key:
Map<String, List<int>> someMap = {
"a": [1],
"b": [2,3],
"c": [4],
};
Now, to add more values, you could simply access the list and add values to it:
someMap["c"].add(5); // c: [4, 5]
someMap["c"].addAll([6,7,8]); // c: [4, 5, 6, 7, 8]

Dart Map manipulation value

Dart Can't change map value from initial map
I have this code :
void main() {
Map tabtest = {
'1' : {
'd' : 'one'
}
};
Map tabtest1 = {};
tabtest.forEach((cle1, val1) {
val1['d']='two';
tabtest1['cle1']=val1;
});
Map tabtest2={};
tabtest.forEach((cle2, val2) {
val2['d']='three';
tabtest2['cle2']=val2;
});
print(tabtest);
print(tabtest1);
print(tabtest2);
}
This code display :
{1: {d: three}}
{1: {d: three}}
{1: {d: three}}
But I want different value from tabtest1 and tabtest2 like :
tabtest1 = {1: {d: two}}
tabtest2 = {1: {d: three}}
Can help me?
Thanks.
There were a couple of problems:
you were actually using the same sub-map {'d': 'one'} in all three versions, instead of creating three seperate maps. The easiest way to copy a Map is to use Map secondMap = Map.from(firstMap). Beware though - this will only copy the first 'level' of the map. See this question for more information
you were using the string 'cle1' instead of it's value, so tabtest1['cle1'] should have been tabtest1[cle1]
void main() {
Map tabtest = {
'1' : {
'd' : 'one'
}
};
Map tabtest1 = {};
// For each map entry in tabtest
tabtest.forEach((cle, val) {
// First COPY the sub-map. If we don't make a copy, we end up
// changing the sub-map in both tabtest and tabtest2
Map val1 = Map.from(val);
// Then we can update the value in our new sub-map:
val1['d']='two';
// And set this as the key '1' in tabtest1
tabtest1[cle]=val1;
});
Map tabtest2={};
tabtest.forEach((cle, val) {
Map val2 = Map.from(val);
val2['d']='three';
tabtest2[cle]=val2;
});
print(tabtest);
print(tabtest1);
print(tabtest2);
}
{1: {d: one}}
{1: {d: two}}
{1: {d: three}}

Flutter:How to merge two objects and sum the values of the same key?

map1 = { "a": 10, "b": 6 },
map2 = { "a": 10, "b": 6, "c": 7, "d": 8 };
Flutter:How to merge two objects and sum the values of the same key?
Do forEach on the longest map and check if the small map contains the key if it does then update the value with the sum or add the new.
map2.forEach((key, value) {
if (map1.containsKey(key)) {
map1[key] = value + map1[key]!;
} else {
map1[key] = map2[key]!;
}
});
map1 will be the final result.
So, if you want to combine/merge the two maps use this code this answer:
final firstMap = {"1":"2"};
final secondMap = {"2":"3"};
final thirdMap = { // here simple adding element to map
...firstMap,
...secondMap,
};
but if you want to make sum and merge use this :
map2.forEach((k, v) {
if (map1.containsKey(k)) { // check if the map has more then 2 values as the 1st one
map1[k] = v + map1[k]!; // if yes so make the some
} else {
map1[k] = map2[k]!; // if no then add the values to map
}
});
as MEET Prajapati asnwer.

Flutter dropdown can't have duplicate values? But unfortunately I have those as it is fetching from an API

My dropdown is having duplicate values as it is fetching Pincode data from an API. Can someone help me to fix this error as the dropdown cant have duplicate values? How to stop duplicate values while fetching the data from the API?enter image description here
You can convert your list to set and then again back to list for to delete duplicated values. Set doesnt contain duplicated values. For more check out documentation of set
void main() {
final myList = [
{
'a': 'apple',
'name':'sam',
'age': 41,
},
{
'a': 'apple',
'name':'alex',
'age': 43,
},
{
'a': 'ban',
'name':'robby',
'age': 41,
}
];
var uniqueIds = myList.map((o) => o["a"]).toSet().toList();
print(uniqueIds);
}
Mapping the list with specific key and then => conversion of toSet() and toList() solves my problem

How to store a simple matrix in Cloud Firestore using Dart/Flutter?

Let's say I have the following integer matrix in Dart:
final List<List<int>> myMatrix = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
];
Then I try to store it in Cloud Firestore like this:
await Firestore.instance.collection("anyCollection").add({
"matrix" : myMatrix,
});
But as soon as I run the code above, the simulator crashes and I get the following error:
*** First throw call stack:
(
0 CoreFoundation 0x00007fff23c4f02e __exceptionPreprocess + 350
1 libobjc.A.dylib 0x00007fff50b97b20 objc_exception_throw + 48
2 Runner 0x000000010e83f8b5 _ZN8firebase9firestore4util16ObjcThrowHandlerENS1_13ExceptionTypeEPKcS4_iRKNSt3__112basic_stringIcNS5_11char_traitsIcEENS5_9allocatorIcEEEE + 581
3 Runner 0x000000010e83edf3 _ZN8firebase9firestore4util5ThrowENS1_13ExceptionTypeEPKcS4_iRKNSt3__112basic_stringIcNS5_11char_traitsIcEENS5_9allocatorIcEEEE + 67
4 Runner 0x000000010e890589 _ZN8firebase9firestore4util20ThrowInvalidArgumentIJEEEvPKcDpRKT_ + 57
5 Runner 0x000000010e959f65 -[FSTUserDataConverter parseData:context:] + 1045
6 Runner 0x000000010e<…>
Lost connection to device.
I am running cloud_firestore: ^0.13.0+1 (currently the latest version) in the pubspec.yaml file. Everything is fine when running the flutter doctor command as well.
What am I doing wrong? Is it even possible to store matrixes in Firestore? If not, can I store that data using another logic?
While you can store an array in Firestore, as mentioned in the documentation, you are not allowed to store another array inside it.
You could take an approach where you store the arrays as fields in a document so you can actually keep each array separated. This is shown over at this thread, or this one.
Hope you find this useful!
The following approach will work for the Matrix you gave as an example, but you won't be able to query the matrix directly from Firestore. You must take the whole matrix out, parse it, and then use it:
final List<List<int>> myMatrix = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
];
// Encode your matrix into a JSON String to add to Firestore
String jsonMatrix = jsonEncode(myMatrix);
// Decode your Json String into a JSON object
var decodedMatrix = jsonDecode(jsonMatrix);
// Decode JSON object back into your matrix
List<List<int>> newList = List<List<int>>.from(decodedMatrix.map((row){
return List<int>.from(row.map((value) => int.parse(value.toString())));
}));
// Print to show that the new object is of the same type as the original Matrix
print(newList is List<List<int>>);
I ended up making the following helper that converts the matrix into a map that's compatible with Firestore:
class MatrixHelper {
// Creates a map that can be stored in Firebase from an int matrix.
static Map<String, dynamic> mapFromIntMatrix(List<List<int>> intMatrix) {
Map<String, Map<String, dynamic>> map = {};
int index = 0;
for (List<int> row in intMatrix) {
map.addEntries([MapEntry(index.toString(), {})]);
for (int value in row) {
map[index.toString()].addEntries(
[MapEntry(value.toString(), true)]
);
}
index += 1;
}
return map;
}
// Creates an int matrix from a dynamic map.
static List<List<int>> intMatrixFromMap(Map<dynamic, dynamic> dynamicMap) {
final map = Map<String, dynamic>.from(dynamicMap);
List<List<int>> matrix = [];
map.forEach((stringIndex, value) {
Map<String, dynamic> rowMap = Map<String, dynamic>.from(value);
List<int> row = [];
rowMap.forEach((stringNumber, boolean) {
row.add(int.parse(stringNumber));
});
matrix.add(row);
});
return matrix;
}
}
It's really simple to use, to save in Firestore it's like this:
final List<List<int>> myMatrix = [
[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
];
await Firestore.instance.collection("anyCollection").add({
"matrix" : MatrixHelper.mapFromIntMatrix(myMatrix),
});
To load the matrix from Firestore, it's like this:
// Loads the DocumentSnapshot:
final document = await Firestore.instance.collection("anyCollection").document("anyDocument").get();
// Retrieves the Matrix:
final List<List<int>> matrix = MatrixHelper.intMatrixFromMap(document.data["matrix"]);