Flutter/Dart - Trying to iterate over a map of values // Syntax help needed - flutter

I'm a self-learning beginner at coding, failing at a self-set task. The aim of the task is ultimately to figure out the syntax...but I spent hours now. So...help pls! Warning: I thoroughly confused myself...so don't expect beauty in my attempt.
I want to use iterate over this map:
const marginsCard = [
{
'ID': 0,
'margins': [
{'marginLeft': 0},
{'marginRight': 5},
{'marginBottom': 0},
{'marginTop': 20},
],
},
{
'ID': 1,
'margins': [
{'marginLeft': 5},
{'marginRight': 0},
{'marginBottom': 0},
{'marginTop': 20,},
],
},
{
'ID': 2,
'margins': [
{'marginLeft': 5},
{'marginRight': 0},
{'marginBottom': 0},
{'marginTop': 20,},
],
},
];
The goals are to
iterate over 'ID'
hand over the values for the margins to a constructor method that
hand back a Card with the specified margins
put those Cards in a list.
The function calling the constructor function in its current state:
buildCardElementList(){
cardElementsList = [
...(marginsCard[int.parse('ID')] as List<Map<String,Object>>).map((cardElement){
return buildCardElement(cardElement['marginLeft'], cardElement['marginRight'], cardElement['marginBottom'], cardElement['marginTop']);
}).toList()];
return cardElementsList;
}
There is so much try and eror in this, I'm sure there are multiple issues. Can someone help me out with clean syntax so I can start to understand what I'm doing again?
Thanks!
EDIT // P.S.: I'm leaving out the receiving/constructing function; it's not the issue.

Enjoy ;)
void main() {
final cards = marginsCard.map(_buildCard).toList();
print(cards);
}
Card _buildCard(Map<String, Object> cardElement) {
return Card(
marginLeft: resolveMargin(cardElement, 'marginLeft'),
marginRight: resolveMargin(cardElement, 'marginRight'),
marginBottom: resolveMargin(cardElement, 'marginBottom'),
marginTop: resolveMargin(cardElement, 'marginTop'),
);
}
num resolveMargin(Map<String, Object> cardElement, String marginName) {
final marginElements = cardElement['margins'] as List<Map<String, Object>>;
return marginElements.firstWhere((marginElement) => marginElement.containsKey(marginName))[marginName] as num;
}
class Card {
final num marginLeft, marginRight, marginBottom, marginTop;
Card({required this.marginLeft, required this.marginRight, required this.marginBottom, required this.marginTop});
#override
String toString() => "marginLeft: $marginLeft; marginRight: $marginRight; marginBottom: $marginBottom; marginTop: $marginTop";
}
const marginsCard = [
{
'ID': 0,
'margins': [
{'marginLeft': 0},
{'marginRight': 5},
{'marginBottom': 0},
{'marginTop': 20},
],
},
{
'ID': 1,
'margins': [
{'marginLeft': 5},
{'marginRight': 0},
{'marginBottom': 0},
{'marginTop': 20,},
],
},
{
'ID': 2,
'margins': [
{'marginLeft': 5},
{'marginRight': 0},
{'marginBottom': 0},
{'marginTop': 20,},
],
},
];

Related

generate category statistics based on a list of Map of expenses in flutter

I have a list of Map of expenses,
Now I want to generate a statistic list that display all category wised expense and number of entries belongs to that category..
I have solved but I felt my code is very kid way...so looking for advance code for this...
here is my code
List<Map<String, dynamic>> expenses = [
{
'category': 'Breakfast',
'amount': 200,
},
{
'category': 'Breakfast',
'amount': 190,
},
{
'category': 'Medicine',
'amount': 400,
},
];
List<Map<String,dynamic>> generate_category_statistics(List<Map<String,dynamic>> list_expense)
{
List<Map<String,dynamic>> resultlist=[];
//want here the code that return a list of map like below output
//[output:
// {category: Breakfast, total: 390, number_of_entries: 2},
// {category: Medicine, total: 400, number_of_entries: 1}],
return resultlist;
}
void main()
{
print("result ="+generate_category_statistics(expenses));
}
You can use collection package like this:
var grouped = groupBy(expenses, (Map value) => value['category']);
var result = grouped.entries
.map((e) => e.value.length > 1
? e.value.reduce((value, element) => {
"category": element["category"],
"total":
(value['amount'] as int) + (element['amount'] as int),
"number_of_entries": e.value.length,
})
: {
"category": e.value.first["category"],
"total": e.value.first["amount"],
"number_of_entries": 1,
})
.toList();
print("result = $result"); //result = [{category: Breakfast, total: 390, number_of_entries: 2}, {category: Medicine, total: 400, number_of_entries: 1}]

Merge value of map and insert it into another map

I have a Map <String,List> map1 that looks like that
{First: ['1', '2', '3', '4'], Second: ['A', 'B']}
I want to create another Map<String,Map<String,int>> as a ruslt of values from map1 to be like that
{'1A' : ['String1':10,'String2':20], '1B' : ['String1':10,'String2':20] , '2A' : ['String1':10,'String2':20], '2B' : ['String1':10,'String2':20], '3A' : ['String1':10,'String2':20] , '3C' : ['String1':10,'String2':20]}
I hope you get my point
Similar question Generate all combinations from multiple lists
Reference Source: https://stackoverflow.com/a/17193002/6576315
void main() async{
Map<String,List> rawMapList = {"First": ['1', '2', '3', '4'], "Second": ['A', 'B']};
List<Map<String, int>> mapResult = [{"String1" : 10}, {"String2" : 20}];
List<String> keyList = <String>[];
generatePermutations(rawMapList.values.toList(), keyList, 0, "");
var result = Map.fromEntries(keyList.map((value) => MapEntry(value, mapResult)));
print(result);
}
void generatePermutations(List<List<dynamic>> lists, List<String> result, int depth, String current) {
if (depth == lists.length) {
result.add(current);
return;
}
for (int i = 0; i < lists.elementAt(depth).length; i++) {
generatePermutations(lists, result, depth + 1, current + lists.elementAt(depth).elementAt(i));
}
}
Try first on DartPad, This code block will print
{1A: [{String1: 10}, {String2: 20}], 1B: [{String1: 10}, {String2: 20}], 2A: [{String1: 10}, {String2: 20}], 2B: [{String1: 10}, {String2: 20}], 3A: [{String1: 10}, {String2: 20}], 3B: [{String1: 10}, {String2: 20}], 4A: [{String1: 10}, {String2: 20}], 4B: [{String1: 10}, {String2: 20}]}
Do upvote reference
the solution
Map<String, dynamic> data = {
'First': ['1', '2', '3', '4'],
'Second': ['A', 'B']
};
Map<String, dynamic> ans = {};
calculate() {
for (var i in (data['First'] as List<dynamic>)) {
for (var j in (data['Second'] as List<dynamic>)) {
ans.addAll({
"$i$j": [
{'String1': 10},
{'String2': 20}
],
});
}
}
log("$ans");
}

Mapbox Changing Polygone Color based users area showed

I'm currently building map using Mapbox GL. On this polygone there is polygone that are color based on 1 metric.
The metric range is between 1 to 25.
I have only 12 color panel.
ColorPannel
The goals would be to
Retrieve to top left, top right, bottom left and bottom right of the users map screen.
Get all the polygone that fit into the area. (SQL request)
From all those polygone, I retrieve the metric MIN and MAX.
Create 12 range of value based of MIN and MAX.
How could I reload the color for each polygone showed on the map based on the 12 range of value that I received from the back-end. This reload of color need to be executed when the users stop moving the area.
Here is my sample of the code :
map.addLayer({
'id': 'terrain1-data',
'type': 'fill',
'source': 'level_hight',
'source-layer': 'sold_level_high-36rykl', 'maxzoom': zoomThresholdZoneHtM, 'paint': {
'fill-color': [
'interpolate',
['linear'],
["to-number",['get', 'MYMETRIC']],
0,
'#FFFFFF',
5,
'#008855',
6,
'#13be00',
7,
'#75e100',
8,
'#aee500',
9,
'#dfff00',
10,
'#fff831',
11,
'#ffe82f',
12,
'#ffd500',
13,
'#ffa51f',
14,
'#ff7b16',
15,
'#ff0a02',
16,
'#c80000'
],
'fill-opacity': [
'case',
['boolean', ['feature-state', 'hover'], false],
0.8,
0.5
],
'fill-outline-color': '#000000',
}
});
Thanks in advance. Sorry I'm starting using Mapbox.
If my understanding is correct, you want to set the number dynamically in 'interpolate'. In the following case you want to change 0, 5, ... according to the data, light?
'fill-color': [
'interpolate',
['linear'],
["to-number",['get', 'MYMETRIC']],
0,
'#FFFFFF',
5,
Then, normally you will get the date from your server and there's a chance to calculate those numbers in JavaScript code. Then put the calculated number in 'interpolate' would work.
Here's a sample. The number is generated randomly,
map.on('load', function () {
map.addSource('maine', {
'type': 'geojson',
'data': {
'type': 'FeatureCollection',
'features': [
{
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [
[[0, 0], [0, 1], [1, 1], [1, 0]]
]
},
'properties': {
'height': 10
}
},
{
'type': 'Feature',
'geometry': {
'type': 'Polygon',
'coordinates': [
[[1, 1], [1, 2], [2, 2], [2, 1]]
]
},
'properties': {
'height': 20
}
},
]
}
});
map.addLayer({
'id': 'maine',
'type': 'fill',
'source': 'maine',
'layout': {},
'paint': {
'fill-color': [
'interpolate',
['linear'],
['to-number', ['get', 'height']],
c(10),
'#000000',
c(10) + 10,
'#FFFFFF',
]
}
});
});
function c(n) {
return Math.round(Math.random() * n);
}

echarts - visualMap according to y axis

I am trying to add a visual map according to the y axis in echarts.
Taking one of their example:
https://echarts.apache.org/examples/en/editor.html?c=area-pieces
The results looks as follow:
what I'm trying to achieve is:
Obviously here, I have just rotated the picture by 90 degree.
How can this be achieve in echarts directly (so not by saving the picture first)?
The simplest solution would be inverting the axis, data index, and visual map axis. See chart options below:
option = {
backgroundColor: '#fff',
xAxis: {
type: 'value',
boundaryGap: [0, '30%'],
position: 'top'
},
yAxis: {
type: 'category',
boundaryGap: false
},
visualMap: {
type: 'piecewise',
show: false,
dimension: 1,
seriesIndex: 0,
pieces: [{
gt: 1,
lt: 3,
color: 'rgba(0, 180, 0, 0.5)'
}, {
gt: 5,
lt: 7,
color: 'rgba(0, 180, 0, 0.5)'
}]
},
series: [
{
type: 'line',
smooth: 0.6,
symbol: 'none',
lineStyle: {
color: 'green',
width: 5
},
markLine: {
symbol: ['none', 'none'],
label: {show: false},
data: [
{yAxis: 1},
{yAxis: 3},
{yAxis: 5},
{yAxis: 7}
]
},
areaStyle: {},
data: [
[200, '2019-10-10'],
[400, '2019-10-11'],
[650, '2019-10-12'],
[500, '2019-10-13'],
[250, '2019-10-14'],
[300, '2019-10-15'],
[450, '2019-10-16'],
[300, '2019-10-17'],
[100, '2019-10-18']
]
}
]
};
Result:
See on Imgur

Dart // Flutter: How to remove Items from List depending on content of entry

In my Flutter app, I have a database which keeps track of which items the user liked and which he disliked. I have the function
List finalFavoritesList;
void queryDb() async {
final db = await database;
final allRows = await db.query(TABLE_FAVORITE);
List finalFavoritesList = allRows.toList(growable: true);
print(finalFavoritesList);
}
which in my understanding creates a dart list from the sqflite database. Logcat prints:
[{id: 0, isFavorite: 0}, {id: 1, isFavorite: 1}, {id: 2, isFavorite: 0}, {id: 3, isFavorite: 1}, {id: 4, isFavorite: 0}, {id: 5, isFavorite: 1}]
Now I want to remove every entry, where isFavorite is equal to 0 but I don't know how. This new list should have another name.
I think your question itself has an answer!
Use removeWhere function.
List favorite = [{'id': 0, 'isFavorite': 0}, {'id': 1, 'isFavorite': 1}, {'id': 2, 'isFavorite': 0}, {'id': 3, 'isFavorite': 1}, {'id': 4, 'isFavorite': 0}, {'id': 5, 'isFavorite': 1}];
favorite.removeWhere((item) => item['isFavorite'] == 0);
print(favorite);
Output:
[{id: 1, isFavorite: 1}, {id: 3, isFavorite: 1}, {id: 5, isFavorite: 1}]
Refer: https://api.dart.dev/stable/2.9.3/dart-core/List/removeWhere.html
Hope that solves your case!