Adding values to map from other map in DART - dart

I have a map like this
Map<String, bool> siSelectedDef = {"1": true, "2": true, "3": false};
I want to loop through the map and check for the key which has a value true, and I want to add those keys inside a List<Map<String, Object>> must
i.e
must contains
[
{
"si" : "1"
},
{
"si" : "2"
}
]
can anyone help me in this, Thanks!

Map<String, dynamic> data = {'a': true, 'b': false, 'c': true};
List<Map<String, dynamic>> _list = [];
data.forEach((key, value) {
if (value) {
_list.add({'si': key});
}
});
print(_list);
please check official doc for more detailed info and other stuffs you can do with Map

Related

I need this object inside the map, but i cant get it

I have this list of maps, and i need to get the 'transactions' value:
final assets = [
{
"name": "BRL", "balance": 150.2,
"transactions" : Transaction(from: "someone", amount: 1)
},
{
"name": "US", "balance": 1100.2,
"transactions" : Transaction(from: "someone", amount: 5)
},
];
i tried to do assets[0]['transactions'], but all i got was null or Instance of 'Transaction'
the class:
class Transaction {
final String id = Random().toString();
final String from;
final double amount;
Transaction({
required this.from,
required this.amount,
});
}
im kinda newbie, then pls help me :)
You can use this dartpad example to view this in an app
Assuming you would like to show your data in a list (since this is a list of maps per the question)
class MyWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ListView.builder(
shrinkWrap: true,
itemCount: assets.length,
itemBuilder: (context, index) {
Transaction data = assets[index]['transactions'];
return
ListTile(
leading: Text(data.amount.toString()),
title: Text(data.from.toString()));
});
}
}

needs to convert Lists of map data into One map

My question is about dart....
the result I got
[{'sam': 8}, {'john': 822}]
I need to convert it into like below
{'sam': 8, 'john': 822}
pls help me.
thanks for reading
Something like this?
void main() {
final listOfMaps = [
{'sam': 8},
{'john': 822},
];
final map = {for (final map in listOfMaps) ...map};
print(map); // {sam: 8, john: 822}
}
Update after example of data has been uploaded
I have made the following example which parses the input you have posted as returns the expected data:
void main() {
final map = {
for (final map in someListOfMaps)
for (final voted in map['voted']! as List<Map<String, String>>)
for (final vote in voted.entries) vote.key: int.parse(vote.value)
};
print(map);
// {60e6956078fb6f42da: 1, 60e6956020d8bf42db: 5, 120d8bf42dffsww66: 1, jd58466daa4dw2: 20, gg4c577x6ad8ds6a: 6}
}
const someListOfMaps = [
{
"voted": [
{"60e6956078fb6f42da": "1"},
{"60e6956020d8bf42db": "5"}
],
"_id": "60e698fe78fb6120d8bf42dd",
"name": "donald"
},
{
"voted": [
{"120d8bf42dffsww66": "1"}
],
"_id": "60e698fe78fb6120d8bf42de",
"name": "barrack"
},
{
"voted": [
{"jd58466daa4dw2": "20"}
],
"_id": "60e698fe78fb6120d8bf42df",
"name": "malan"
},
{
"voted": [
{"gg4c577x6ad8ds6a": "6"}
],
"_id": "60e698fe78fb6120d8bf42e0",
"name": "kuma"
}
];
This is a longer approach and probably more understandable.
// the result I got [{'sam': 8}, {'john': 822}]
// I need to convert it into like below {'sam': 8, 'john': 822}
void main() {
final mapList = [{'sam': 8}, {'john': 822}];
print(mapListToJustMap(mapList)); // output: {sam: 8, john: 822}
// The <int> is not required
print(genericMapListToJustMap<int>(mapList)); // output: {sam: 8, john: 822}
}
Map<String, int> mapListToJustMap(List<Map<String, int>> mapList) {
// Create a new empty map object
final newMap = <String, int>{};
// Iterate through the mapList input
for (final singleMap in mapList) {
// add the current iteration to the new map object
newMap.addAll(singleMap);
}
return newMap;
}
// A generic approach
Map<String, T> genericMapListToJustMap<T>(List<Map<String, T>> mapList) {
// Create a new empty map object
final newMap = <String, T>{};
// Iterate through the mapList input
for (final singleMap in mapList) {
// add the current iteration to the new map object
newMap.addAll(singleMap);
}
return newMap;
}

toJson() invalid when recursively encode tree data structure

I have a Dart class that I am using as a node class for a tree data structure.
My goal here is to encode objects of this class and its child nodes recursively.
I have a toJson() method that takes the child Nodes List and calls jsonencode on them.
class Node{
String name;
Map<String, String> attributes;
List<Node> children = List<Node>();
Node(this.name, attributes) {
this.attributes = attributes;
this.children = List<Node>();
}
Node.fromJson(Map<dynamic,dynamic> _map) {
this.name = _map['name'];
this.children = new List<Node>();
this.attributes = _map['attributes'][0];
for(var i = 0; i < _map['children'].length;i++){
Node temp = new Node.fromJson(_map['children'][i]);
this.addChild(temp);
}
}
Map<String, dynamic> toJson() => {
'name': name,
'attributes': [attributes],
'children': [
...this.children.map(jsonEncode)
]
};
}
I have a unit test i created to test this functionality:
Node nodeMap = {
"name": "Name",
"attributes": [
{"#htag1": "tagval1"}
],
"children": [
{
"name": "NameChild1",
"attributes": [
{"#htag2": "tagval2"}
],
"children": []
},
{
"name": "NameChild2",
"attributes": [
{"#htag3": "tagval3"}
],
"children": []
}
]
};
UNode unodeInst = new UNode.fromJson(nodeMap);
// Act
var nodeCreate = nodeInst.toJson();
// Assert
expect(nodeCreate, equals(nodeMap));
Here is the output of my unit test
Expected: {
'name': 'Name',
'attributes': [{'#htag1': 'tagval1'}],
'children': [
{
'name': 'NameChild1',
'attributes': [{'#htag2': 'tagval2'}],
'children': []
},
{
'name': 'NameChild2',
'attributes': [{'#htag3': 'tagval3'}],
'children': []
}
]
}
Actual: {
'name': 'Name',
'attributes': [{'#htag1': 'tagval1'}],
'children': [
'{"name":"NameChild1","attributes":[{"#htag2":"tagval2"}],"children":[]}',
'{"name":"NameChild2","attributes":[{"#htag3":"tagval3"}],"children":[]}'
]
}
Which: at location ['children'][0] is '{"name":"NameChild1","attributes":[{"#htag2":"tagval2"}],"children":[]}' which expected a map
As you see its not encoding my object correctly.
I believe this is happening because when i reclusively call jsonencode this method returns a string that is placed into the children array.
I believe part of my problem is that i dont fully understand the d diffrence between jsonencode() and toJson().
It is my understanding that jsonencode() calls toJson().. but jsonencode() returns a string and toJson() returns a Map<String, dynamic>.. so i think what i want here is to call toJson() recursively and not jsonencode.
Does this sound correct?
But i cannot figure out how to do this on a list in this situation.
I have tried the following
...this.children.map(this.toJson())
but i get "The argument type 'Map<String, dynamic>' can't be assigned to the parameter type 'dynamic Function(Node)'"
...this.children.forEach((element) {element.toJson()})
but i get "Spread elements in list or set literals must implement 'Iterable'"
Does this mean i have to implement the Iterable interface in my class?
You're just using the map method incorrectly. Use the following instead.
[
...this.children.map((e) => e.toJson())
]
It's also unnecessary to use spread with a literal list or use this. You can simplify the code to just
children.map((e) => e.toJson()).toList()

Convert JSON to List<Map<String, List<String>>> without overusing dynamic

Given the following JSON string
[
{
"popular": []
},
{
"recommended": [
"privacy",
"security",
"IFTTT",
"mobile",
"location",
"Pocket",
"advertising",
"Instapaper",
"data",
"surveillance"
]
}
]
How would I go about converting this to List<Map<String, List<String>>> without overusing dynamic?
This is what I have currently:
response // List<dynamic>
.map((i) => (i as Map<String, dynamic>).map((String key, dynamic value) =>
MapEntry<String, List<String>>(key, List<String>.from(value))))
.toList();
This is about as minimal as I can get it - the static type is correctly List<Map<String, List<String>>> with only a bit of repetition with the as casts.
var typed = (response as List) //skip this `as` if it's already a List
.map((v) => (v as Map)
.map((k, v) => MapEntry<String, List<String>>(k, List.from(v))))
.toList();
Inference fills in the rest for you.

Flutter How To Update/Add Value to a Key in a Map<K,V>

Currently I have a map that looks like this to send emails via an API:
Map body = {"personalizations": [
{
"to": [
{
"email": "$receiverEmail"
}
],
"dynamic_template_data": {
"EmployeeName": "$employeeName",
"EmployeeID": "$employeeID",
"PatientName": "$patientName",
"ProviderName": "$providerName",
"TreatmentDate": "$treatmentDate",
"Diagnosis": "$diagnosis"
}
}
],
"from": {
"email": "$userEmail"
},
"template_id": "$templateID"
};
I am planning to use this structure with 2 forms of emails and for that to happen I need to update/add values under the dynamic_template_data key.
Therefore I am trying to find out how I could update/add value to that specific key. I found a function called Map.update() but I am unsure as how to properly use it. How do I approach this problem?
Just assign a new value to a specific key to update.
body['personalizations'][0]['dynamic_template_data']['EmployeeName'] = 'John Doe';
or
body['personalizations'][0]['dynamic_template_data']['Salary'] = 5000.00;
another example to do an assignment only if it doesn't exist yet
(body['personalizations'][0] as Map).putIfAbsent('Salary', () => 5000.00);
Map.update() and Map.updateAll() is a predefined function for this.
Map<String, bool> filterMap = {
'All': true,
'Open': false,
'Inprocess': false,
'Resolved': false,
'Closed': false,
};
just use this to set all value pairs to false :-
filterMap.updateAll((key, value) => value = false);
OUTPUT :
[MapEntry(All: false), MapEntry(Open: false), MapEntry(Inprocess: false), MapEntry(Resolved: false), MapEntry(Closed: false)]
In case you want to change a single value :-
filterMap.update(filterMap.keys.toList()[index]),(value) => value = true);
(filterMap.keys.toList()[index]) -> this is key name. I have used it in list. So, to find a element on which user tapped, I have used this. You can give a key name there.
filterMap.update('Open'),(value) => value = true);
OUTPUT :
[MapEntry(All: false), MapEntry(Open: true), MapEntry(Inprocess: false), MapEntry(Resolved: false), MapEntry(Closed: false)]

Resources