How to add a new value to Map in Dart? - flutter

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]

Related

How to add data to an MUI table column-wise instead of row-wise?

Good day! Here is the sandbox react code that I'm using for a project involving MUI tables:
I have been racking my brain over this, but can't seem to get a solution. How can I add to this table column-wise instead of by row?
In line 57-67, the rows are created first and then they are populated row-wise, left-to-right by data.
The data given looks like this:
const data = [
{name: "sample_name",
calories: "19",
fat: "90",
carbs: 70,
protein: 90},
{name: "sample_name",
calories: "19",
fat: "90",
carbs: 70,
protein: 90},
]
What the lines I mentioned do is it takes 1 of the objects in the data and appends them row-wise
I work with a data that looks like this:
const name = ["richard","nixon"]
const calories = [9, 9, 0, 9, 0, 5, 8]
const fat = [10, 9 , 9]
const carbs = [11, 3, 4,5 ]
const protein = [1, 1]
I just want to be able to insert name data into the name column... and so on... this should also hopefully make it easier for me to dynamically insert more data for each column using TextField+button action
Seems to me like this is a data issue, not Material UI. You need to provide row and column data to a table, regardless of what library you use, that's just how tables are build. So if you are getting back data by columns, you need a reducer or a method to convert them into rows. Here is a super quick and dirty example:
const rawData = {
name: ["Ice cream", "Sno cone"],
calories: [32, 45]
};
let columns = Object.keys(rawData);
let rows = rawData.name.map((name, i) => {
return { name, calories: rawData.calories[i] };
});
/*
rows = ["name", "calories"]
columns = [
{ name: "Ice cream", calories: 32 },
{ name: "Sno cone", calories: 45 },
];
*/
Obviously, this is a quick example and not very extensible, but should lead you in a good direction. Perhaps a reducer which could build out row data more elegantly. However, this will allow you to build out the table as intended:
<TableContainer component={Paper}>
<Table>
<TableHead>
<TableRow>
{columns.map((i) => (
<TableCell>{i}</TableCell>
))}
</TableRow>
</TableHead>
<TableBody>
{rows.map((row) => (
<TableRow key={row.name}>
<TableCell>{row.name}</TableCell>
<TableCell>{row.calories}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>

Dart - For loop is changing elements of my list even when it is cloned

When I access to the elements of my list in a for loop, I would like to be able to modify them without impacting the original list.
Here's a simple example :
List pairs = [
[1,8],
[1,6],
];
print(pairs);
List copy = List.from(pairs);
for (List pair in copy) {
if(pair.contains(1)) {
pair.remove(1);
}
}
print(pairs);
The output of this is :
[[1, 8], [1, 6]]
[[8], [6]]
I expected the output to be :
[[1, 8], [1, 6]]
[[1, 8], [1, 6]]
I tried to replace List copy = List.from(pairs); with :
List copy = [...pairs]; // This
List copy = []..addAll(pairs); // Or this
Nothing is working.
The only solution I found was to do this :
List temp = List.from(pair);
if(temp.contains(1)) {
temp.remove(1);
}
But it seems to be a bit overkill. Does anyone has another idea ?
As jamesdlin says, using List.from or the spread operator just creates a shallow copy of the list. Dart does not have a built-in deep copy function that I could find, but if you'll only be working with nested lists like this we can define our own pretty easily:
List<T> deepCopy<T>(List<T> list) =>
list.map((e) => e is List ? deepCopy(e) : e).cast<T>().toList();
Here's a dartpad showing the result.

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

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

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.

How to convert a `List` to `Set` using literals

final _set = [1, 1, 2, 3, 4].toSet();
besides effective dart suggesting prefer_collection_literals
it really looks like java or c# rather than dart (no offense)
does anybody knows
How to convert a List to Set using literals
(suggesting to add // ignore: prefer_collection_literals isn't an answer)
You can do something like this:
main() {
final list = [1, 1, 2, 3, 4];
final _set = {...list};
print('set: $_set'); // set: {1, 2, 3, 4}
}
You can write the same code as final _set = {1, 1, 2, 3, 4};.
When you write {key: value, key: value} that is a Map literal, but if you just do {value, value, ...} that becomes a Set literal.