Flutter sort list by value - list

how i can sort my List by one of my values from list?
here is a example of my list
List data = [
{'name': 'Example1', 'value1': 10, 'value2': 0},
{'name': 'Example2', 'value1': 0, 'value2': 10},
{'name': 'Example3', 'value1': 15, 'value2': 5},
{'name': 'Example4', 'value1': 22.5, 'value2': 10},
];
and so I call it
Column(
children: data.map((info) {
return Container(
child: SizedBox(
child: Row(
children: [
Text(info['name'],),
Text(info['value1'],),
],
),
),
);
}).toList())
this is how my list is listed from top to bottom
how can i sort it by value?
How can I hide an entry if the value is 0?

list.sort() takes a comparator function. A comparator takes two values from the list and compares them to see if swapping is required. Based on what you return, you can control how the lists get sorted. When a positive value is returned, swapping occurs otherwise not.
In your case, let's say you want to sort using value1 in increasing order. You need to tell the comparator to return a positive value when a > b. If you want decreasing order, return a positive value when b > a:
List data = [
{'name': 'Example1', 'value1': 15},
{'name': 'Example2', 'value1': 10},
{'name': 'Example3', 'value1': 5},
{'name': 'Example4', 'value1': 0},
];
// sort in place w.r.t. value1
// CompareTo method just returns first value - second value in case of double
// Try returning b['value1'].compareTo(a['value1']) or b['value1'] - a['value1'] and the result should be in descending order w.r.t value1 property.
data.sort((a,b) => a['value1'].compareTo(b['value1'])); // You can also write a['value1'] - b['value1']
print(data.toString());
// To filter (remove all those elements whose value1 is 0)
List filtered = data.where((a) => a['value1'] != 0).toList(); // Where method takes a function which should return true if you want to keep the item in the filtered list.
print(filtered.toString()); // filtered is the new list with all those elements removed.
and here is the output:
[{name: Example4, value1: 0}, {name: Example3, value1: 5}, {name: Example2, value1: 10}, {name: Example1, value1: 15}]
[{name: Example3, value1: 5}, {name: Example2, value1: 10}, {name: Example1, value1: 15}]
Update:
You can use the filter like this:
Column(
children: data
.where((d) => d['value1'] != 0) // <----- Here :)
.map((info) {
return Container(
child: SizedBox(
child: Row(
children: [
Text(info['name'],),
Text(info['value1'],),
],
),
),
);
}).toList())

Related

How to do a "Zoom to me" function to filter/scroll down on a list in flutter for a leaderboard?

I'm trying to make a leaderboard for a list of users and as a quick way for the current user to find what his rank is I made a button which should filter/scroll down in the list and get the first 5 users that are ahead/onTop of the current user and then the 4 other users that rank behind him in the list while the current user should be in the middle.
I tried to play around with lists and tried to filter them but I don't have much to show I found this 2 links here and here and got some ideas from them this is what I got so far:
My lists:
bool _isZoomed = false;
List<int> items = [
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
];
List<int> _filteredItems = [];
My function:
zoomOnMe() {
List<int> _users = [];
_users.addAll(items);
_users.retainWhere(
(user) {
var _zoom = items.takeWhile((i) => i <= 5);
_isZoomed = true;
return _zoom.contains(user);
},
);
setState(() {
_filteredItems = _users;
});
}
My widgets:
TextButton(
onPressed: zoomOnMeBiach,
child: const Text('Zoom on me biach'),
),
Expanded(
child: ListView.builder(
shrinkWrap: true,
itemCount:
_isSearching == true ? _filteredItems.length : items.length,
itemBuilder: (context, index) {
return ListTile(
title: Text(
_isSearching == true
? _filteredItems[index].toString()
: items[index].toString(),
),
);
},
),
),
What I got:
What I want:

sorting a dictionary based on specific key value

I get data from the a source which I store in variable d
d = {
'0174':
{
'exists': 'Yes',
'order': 4,
},
'0171':
{
'order': 1,
},
'0080': {
'exists': 'Yes',
'order': 0,
},
'0173':
{
'exists': 'No',
'order': 3,
},
'0172':
{
'exists': 'Yes',
'order': 2,
}
}
I have written the below logic that somewhat works,
for w in sorted(d, key=d.get, reverse=True):
print(w, d[w]["shot_order"])
but not perfect.
I want to be able to sort based on the order key in the dict
please help.
You need to use key=lambda outer_key: d[outer_key]['order'] as the sorting key:
for w in sorted(d, key=lambda outer_key: d[outer_key]['order'], reverse=True):
print(w)
Outputs
0174
0173
0172
0171
0080

Inquiry about using if statement with Widget what these dots meaning if(condition) ...[ ]

Inquiry about using if statement with Widget.What these three dots meaning if(condition) ...[something ]
For example:
if (_imageFile != null) ...[
Image.file(
_imageFile,
height: MediaQuery.of(context).size.height /4,
width: MediaQuery.of(context).size.width,
),
Row(
children: <Widget>[
Expanded(
child: FlatButton(
child: Icon(Icons.crop),
onPressed: _cropImage,
),
),
Expanded(
child: FlatButton(
child: Icon(Icons.refresh),
onPressed: _clear,
))
],
),
Uploader(file: _imageFile) ]
... is the spread operator. It adds all the items of an iterable inside another list, such that:
[
'a',
...['b', 'c,'],
'd',
]
gives ['a', 'b', 'c', 'd'].
The if placed before just makes it conditional, such that the items are not added to the list if the condition fails.
The answer is at https://dart.dev/guides/language/language-tour#lists
basically it will add all the content of the list after the '...' operator to the current list.
var list1 = [1, 2, 3];
var list2 = [0, ...list];
///list2 becomes [0, 1, 2, 3]
more at https://github.com/dart-lang/language/blob/master/accepted/2.3/spread-collections/feature-specification.md

Column Chart in Google Charts is displaying bars 10 times proper height

I can't figure out why, I've triple checked that I'm passing in the right values. When I hover over any of the bars it displays the right data, but every single one of them displays at 10x scale on the graph and I can't figure out why. Here's my code if it helps:
var dashboard2 = new google.visualization.Dashboard(
document.getElementById('dashboard'));
var control2 = new google.visualization.ControlWrapper({
'controlType': 'ChartRangeFilter',
'containerId': 'control2',
'options': {
// Filter by the date axis.
'filterColumnIndex': 0,
'ui': {
'chartType': 'LineChart',
'chartOptions': {
'chartArea': {'width': '80%'},
'hAxis': {'baselineColor': 'none'}
},
// Display a single series that shows the closing value of the stock.
// Thus, this view has two columns: the date (axis) and the stock value (line series).
'chartView': {
'columns': [0, 1, 14]
},
// 1 day in milliseconds = 24 * 60 * 60 * 1000 = 86,400,000
'minRangeSize': 259200000
}
},
// Initial range: 2012-02-09 to 2012-03-20.
'state': {'range': {'start': new Date(2012, 11, 7), 'end': new Date()}}
});
var chart2 = new google.visualization.ChartWrapper({
'chartType': 'ComboChart',
'containerId': 'chart2',
'options': {
// Use the same chart area width as the control for axis alignment.
'chartArea': {'height': '80%', 'width': '80%'},
'hAxis': {'slantedText': false},
'vAxis': {'viewWindow': {'min': 0, 'max': 400}},
'title': 'Sales Made by Affiliate Name',
'seriesType': "bars",
'series': {0: {type: "line"}, 13: {type: "line"}},
'isStacked': true
},
// Convert the first column from 'date' to 'string'.
'view': {
'columns': [
{
'calc': function(dataTable, rowIndex) {
return dataTable.getFormattedValue(rowIndex, 0);
},
'type': 'string'
}, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
}
});
var jsonData2 = $.ajax({
url: "getData.php",
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server
var data2 = new google.visualization.DataTable(jsonData2);
dashboard2.bind(control2, chart2);
dashboard2.draw(data2);
Edit: Here's a small bit of the data at the very beginning, because I don't want to give out our data, but I suppose it might be necessary to get an idea for what is being passed in. I cut out the starting bracket for readability:
"cols":[ {"id":"","label":"Date","pattern":"","type":"date"}, {"id":"","label":"Total","pattern":"","type":"number"}, {"id":"","label":"andersce99","pattern":"","type":"number"}, {"id":"","label":"sojourn","pattern":"","type":"number"}, {"id":"","label":"warriorplus","pattern":"","type":"number"}, {"id":"","label":"potpie queen","pattern":"","type":"number"}, {"id":"","label":"60minuteaffiliate","pattern":"","type":"number"}, {"id":"","label":"bob voges","pattern":"","type":"number"}, {"id":"","label":"Grayth","pattern":"","type":"number"}, {"id":"","label":"TiffanyDow","pattern":"","type":"number"}, {"id":"","label":"AmandaT","pattern":"","type":"number"}, {"id":"","label":"Gaz Cooper","pattern":"","type":"number"}, {"id":"","label":"Sam England","pattern":"","type":"number"}, {"id":"","label":"Matthew Olson","pattern":"","type":"number"}, {"id":"","label":"Average Per Day Over Time","pattern":"","type":"number"} ],
"rows": [ {"c":[{"v":"Date(2012,11,7)","f":null},{"v":"387","f":null},{"v":"19","f":null},{"v":"275","f":null},{"v":"8","f":null},{"v":"0","f":null},{"v":"35","f":null},{"v":"3","f":null},{"v":"21","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"11","f":null},{"v":"6","f":null},{"v":"387","f":null}]},
{"c":[{"v":"Date(2012,11,8)","f":null},{"v":"98","f":null},{"v":"11","f":null},{"v":"39","f":null},{"v":"1","f":null},{"v":"0","f":null},{"v":"15","f":null},{"v":"0","f":null},{"v":"7","f":null},{"v":"9","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"3","f":null},{"v":"6","f":null},{"v":"242.5","f":null}]},
{"c":[{"v":"Date(2012,11,9)","f":null},{"v":"58","f":null},{"v":"7","f":null},{"v":"16","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"4","f":null},{"v":"0","f":null},{"v":"3","f":null},{"v":"10","f":null},{"v":"2","f":null},{"v":"9","f":null},{"v":"0","f":null},{"v":"2","f":null},{"v":"181","f":null}]},
{"c":[{"v":"Date(2012,11,10)","f":null},{"v":"196","f":null},{"v":"5","f":null},{"v":"8","f":null},{"v":"126","f":null},{"v":"0","f":null},{"v":"2","f":null},{"v":"35","f":null},{"v":"0","f":null},{"v":"7","f":null},{"v":"4","f":null},{"v":"3","f":null},{"v":"1","f":null},{"v":"0","f":null},{"v":"184.75","f":null}]},
{"c":[{"v":"Date(2012,11,11)","f":null},{"v":"76","f":null},{"v":"7","f":null},{"v":"5","f":null},{"v":"17","f":null},{"v":"30","f":null},{"v":"7","f":null},{"v":"1","f":null},{"v":"1","f":null},{"v":"2","f":null},{"v":"1","f":null},{"v":"4","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"163","f":null}]},
{"c":[{"v":"Date(2012,11,12)","f":null},{"v":"48","f":null},{"v":"4","f":null},{"v":"5","f":null},{"v":"9","f":null},{"v":"20","f":null},{"v":"7","f":null},{"v":"1","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"143.833333333","f":null}]},
{"c":[{"v":"Date(2012,11,13)","f":null},{"v":"21","f":null},{"v":"3","f":null},{"v":"2","f":null},{"v":"5","f":null},{"v":"4","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"1","f":null},{"v":"2","f":null},{"v":"0","f":null},{"v":"1","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"126.285714286","f":null}]},
{"c":[{"v":"Date(2012,11,14)","f":null},{"v":"12","f":null},{"v":"1","f":null},{"v":"1","f":null},{"v":"2","f":null},{"v":"4","f":null},{"v":"2","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"112","f":null}]},
{"c":[{"v":"Date(2012,11,15)","f":null},{"v":"8","f":null},{"v":"3","f":null},{"v":"0","f":null},{"v":"1","f":null},{"v":"2","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"1","f":null},{"v":"0","f":null},{"v":"1","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"0","f":null},{"v":"100.444444444","f":null}]}
Your data is formatted incorrectly: numbers need to be stored as numbers in the JSON, not as strings. As an example, this:
{"v":"387","f":null}
should be like this:
{"v":387,"f":null}
If you are using PHP's json_encode function to build the JSON, you can add JSON_NUMERIC_CHECK as an argument to the function call to output the numbers properly:
json_encode($myData, JSON_NUMERIC_CHECK);

What's an efficient way to filter this array?

My data structure is
companies = [
{name: 'A', ramps: [1, 2]},
{name: 'B', ramps: [3, 4, 5]}
...
]
ramps = [
{id: 1, division: 'accounting', amount: 500},
{id: 2, division: 'sale', amount: 200},
...
]
My goal is to end up with the following data:
groupedByDivision = [
{division: accounting, total: 12000},
{division: sales, total: 6500},
..
]
My first brute-force approach is something like this (note: I've extended Ember.Array with this flatten method:
var ramps = this.get('controller.companies') // this is the array of companies
.get('model')
.mapProperty('ramps')
.flatten();
var temp = {}, data = [];
$.each(ramps, function(index, ramp) {
if ( !(ramp.billingDiv in tempCompanies) ) {
temp[ramp.billingDiv] = ramp.feeChange;
} else {
temp[ramp.billingDiv] += ramp.feeChange;
}
});
$.each(temp, function(division, amount) {
data.push({
'category': division,
'count': amount
});
});
return data;
Any other suggestions? I'm not too familiar with the Ember.Array methods yet, so I'm not aware of all their use cases.