I have a flutter widget I am working on, and I want the options to be 0-99 by .25 increments. I'm pretty sure you use the generate function, but I can't figure out how to get it in the particular format I am using. What data type is it? etc. Can someone please take a look?
Widget _Display(display) {
if (display == true){
return Expanded(
child: ChoicesWidget(
Options: [
{
"display": "1", //these are the values I want to go from 0-99 by increments of .25.
"value": 1,
"checked": false
},
{
"display": "1.25",
"value": 1.25,
"checked": false
}
]
),);
}
else return Container();
}
Thanks!
Try a while loop and gen something for you:
Widget _Display(display) {
var min = 0.0;
var max = 99.0;
var current = min;
List<Map<String, Object>> options = [];
while (current <= max) {
options.add(
{
"display": current.toString(),
"value": current,
"checked": false,
},
);
current += 0.25;
}
if (display == true) {
return Expanded(
child: ChoicesWidget(Options: options),
);
} else {
return Container();
}
}
Related
How to get an average number of star (means result should get 1.5) ?
Note: The value to get is without index because it is not under ListView.builder
Below is the sample json code and this is how what i tried till now.
JSON
{
"message": "feedbacks for restaurant branch returened",
"data": [
{
"id": "4",
"comment": "Investor Operations Coordinator",
"star": 1,
}
{
"id": "4",
"comment": "Investor Operations Coordinator",
"star": 2,
}
]
}
DART
Widget buildReviewNumbers(List<FeedbacksData> data) {
return Column(
children: [
for (int index = 0; index < data.length; index++)
Text(
data[index].star.toString(),
style: TextStyle(fontWeight: FontWeight.w900, fontSize: 30.0),
),
],
);
}
paste it on DartPad
final map = {
"message": "feedbacks for restaurant branch returened",
"data": [
{
"id": "4",
"comment": "Investor Operations Coordinator",
"star": 1,
},
{
"id": "4",
"comment": "Investor Operations Coordinator",
"star": 2,
}
]
};
void main() {
final data = map['data'] as List<Map<String, dynamic>>;
var total = 0;
data.forEach((e) {
total += e['star'] as int;
});
print(total/ data.length);
}
For your case:
Widget buildReviewNumbers(List<FeedbacksData> data) {
var total = 0;
data.forEach((e) {
total += e.star;
});
return Text(
'${total/data.length}',
style: TextStyle(fontWeight: FontWeight.w900, fontSize:30.0),
);
}
Your jsondata of type Map dynamic has to be converted to a list of Feedbacks according to your code. Once done just use the map operator to loop through your data.
Column(
children: data.map((item) => Text(item.star.toString())).toList();
);
For lack of more info on what Feedbacks data looks like i shortened it to this.
You can use reduce to get the total value of ratings, then divide it by the number of ratings. See the concrete example on DartPad.
I have a list with this data and I want to transform this in a Map<DateTime, List> with as variable for event (_id, title, date, active), ere is an example of data that I recover:
[
{
"_id":8,
"title":"Matin",
"date":"2021-08-04T00:00:00.000Z",
"active":1
},
{
"_id":9,
"title":"Après-midi",
"date":"2021-08-04T12:00:00.000Z",
"active":1
},
{
"_id":11,
"title":"Matin",
"date":"2021-08-05T00:00:00.000Z",
"active":1
},
{
"_id":12,
"title":"Après-midi",
"date":"2021-08-05T12:00:00.000Z",
"active":1
},
{
"_id":6,
"title":"Matin",
"date":"2021-08-11T00:00:00.000Z",
"active":1
},
{
"_id":7,
"title":"Après-midi",
"date":"2021-08-11T12:00:00.000Z",
"active":1
},
{
"_id":4,
"title":"Matin",
"date":"2021-08-17T00:00:00.000Z",
"active":1
},
{
"_id":10,
"title":"Matin",
"date":"2021-08-17T00:00:00.000Z",
"active":1
}
]
And in each value I have a date with year, month, day and time and I would like to group the dates without taking the hour into account, what will look like this:
"2021-08-04": [
{
"_id":8,
"title":"Matin",
"date":"2021-08-04T00:00:00.000Z",
"active":1
},
{
"_id":9,
"title":"Après-midi",
"date":"2021-08-04T12:00:00.000Z",
"active":1
}
],
"2021-08-05": [
[
{
"_id":11,
"title":"Matin",
"date":"2021-08-05T00:00:00.000Z",
"active":1
},
{
"_id":12,
"title":"Après-midi",
"date":"2021-08-05T12:00:00.000Z",
"active":1
}
]
I try to do something with Map.fromIterable but I have some error...
If someone can help me thanks !
I brute-forced the solution type you need. The provided solution will work for sure if the format of the date stored doesn't change.
void converter(var data) {
var req={};
for (int i = 0; i < data.length; i++) {
var date=data[i]["date"].toString().substring(0,10);
if(!req.containsKey(date))
req[date]=[];
req[date].add(data[i]);
}
print(req);
}
As you are using flutter there is a package that can handle this of stuff.
https://pub.dev/packages/collection
you will need groupby.
i did something like that, idk if the api is still the same. Anyhow here is the snippet.
.map(
(List<Appointment> appointments) {
appointments.sort(
(Appointment a, Appointment b) {
if (a.appointmentdate
.difference(b.appointmentdate)
.isNegative) return -1;
return 1;
},
);
return appointments;
},
).distinct();
Considering that data is the List<Map<String, Object>> variable you listed, i.e. assuming your data is not a JSON object, I'd do:
Map<String, List<Map<String,Object>>> myTfData = {}
data.forEach(
(value) {
var myDate = value['date'] as String;
if(myTfData.containsKey(myDate)) myTfData[myDate] = [];
myTfData[myDate]!.add(value);
}
);
You'd obtain a Map<String, List<Map<String,Object>>> object as requested.
I'm using an API which returns the value like this.
[
{
"store": "AMAZON"
},
{
"store": "FLIPKART"
},
{
"store": "WALMART"
},
{
"store": "ALIBABA"
},
]
I need this to be in a drop down.
I need a drop down button with this API data in it. Some one help please. I have tried many ways but nothing worked.
nigale try code:
List<String> markets = []; // Or var markets = [];
String _mySelection;
#override
void initState() {
buidDropDownItems();
super.initState();
}
//
void buidDropDownItems() async {
markets = await retrievedata.getMarket();
// Refresh the UI if the State object has been created
if(mounted){
setState(() {});
}
}
child: DropdownButton(
items: markets.map<DropdownMenuItem<String>>((String val){
return DropdownMenuItem<String>(value: val, child: Text(val));
}).toList(), // Get items from the available data in markets variable
onChanged: (sto) {
setState(() {
_mySelection = sto;
});
},
value: _mySelection,
hint: Text('Please select the store: '),
),
The function retrievedata.getMarket(); is returning Future<dynamic> which dynamic is your markets list.
let's say that this array is retrieved in a variable called data
List<String>list=[];
for(var itemData in data){
list.add(itemData['store']);
}
And wala, Now list conation array of String ready to be used
I have included my code below. While it is sort of working, ill get to that in a minute, I feel like there is a better, more efficient, more correct, way to achieve my goal. I have a map for different weather options, in this case, Tornado, Severe Weather and Flash flood warnings. These are all included in one geojson file. The geo json file has a property called LayerId. This determines the time in the loop that the layer would show. I have a simple global map loop that constantly runs from 0 - 11. So if I am on loop 5, then only the data that corresponds with LayerId 5 would be visible. All others would be hidden/removed (which ever is preferred). When the loop hits 6, the layer corresponding to LayerId 5 would go away and LayerId 6 would now show and so on. Once the loop reaches 11, it starts over at 0.
I am not using a leaflet control due to the site requirements so i am using my own simple check box controls. when the check box is clicked, it calls a toggleLayer function to apply filters to my data. If FlashFlood is checked then only the data corresponding to the flash flood would show over the course of the loop IF it has data for flash flood at that interval.
When i said that it is sort of working...in my loop function i have a call to remove a layer. this works except every now and then it throws a null or undefined error. problem is is that its never the same layer. each time i start the application, its a different layer that errors out.
Below i have included a sample of my geojson and the code. The entry point for the code is at the toggleLayer function.
Thanks for any and all help.
GEOJSON FILE
{
"name": "WarningsJson",
"type": "FeatureCollection",
"features": [
{
"type": "Feature",
"geometry": {
"coordinates": [
[
[ -86.00, 31.00 ],
[ -86.00, 32.00 ],
[ -87.00, 30.00 ],
[ -86.00, 31.00 ]
]
],
"type": "Polygon"
},
"properties": {
"type": null,
"strokeColor": "#ff9aa3",
"StartDateTime": "09/29/2020 7:30:00 AM",
"EndDateTime": "09/29/2020 9:30:00 AM",
"strokeThickness": 20,
"InfoboxTitle": "SFFW",
"Station": "KMOB",
"Identifier": "FFW",
"LayerId": "0"
}
},
{
"type": "Feature",
"geometry": {
"coordinates": [
[
[ -87.00, 32.00 ],
[ -87.00, 33.00 ],
[ -88.00, 31.00 ],
[ -87.00, 32.00 ]
]
],
"type": "Polygon"
},
"properties": {
"type": null,
"strokeColor": "#c0ffd4",
"StartDateTime": "09/29/2020 7:30:00 AM",
"EndDateTime": "09/29/2020 9:30:00 AM",
"strokeThickness": 2,
"InfoboxTitle": "TOR",
"Station": "KMOB",
"Identifier": "TOR",
"LayerId": "1"
}
},......
APPLICATION CODE
var WarnStormModel = (function () {
var layer0 = new L.LayerGroup();
var layer1 = new L.LayerGroup();
var layer2 = new L.LayerGroup();
var layer3 = new L.LayerGroup();
var layer4 = new L.LayerGroup();
var layer5 = new L.LayerGroup();
var layer6 = new L.LayerGroup();
var layer7 = new L.LayerGroup();
var layer8 = new L.LayerGroup();
var layer9 = new L.LayerGroup();
var layer10 = new L.LayerGroup();
var layer11 = new L.LayerGroup();
var warnConditionsLayersGroup = [layer0, layer1, layer2, layer3, layer4, layer5, layer6, layer7, layer8, layer9, layer10, layer11];
var tornadoActive = false;
var svrActive = false;
var ffwActive = false;
const WarnFilter = {
tornado: null,
svr: null,
flood: null
}
function init() {
$.getJSON('/Data/GeoJsonFiles/WarningJsons/Warnings_0.json', function (data) {
L.geoJSON(data, {
style: function (feature) {
return {
color: feature.properties.strokeColor,
fillOpacity: 0
};
},
pane: "warnPane",
onEachFeature: function (feature, layer) {
var popupText = '<div>'
+ '<span style="float: right; cursor: pointer; cursor: hand"</i></span><br>'
+ '<b>LAYER: </b>' + layer.feature.properties.LayerId + '<br>'
+ '<b>TYPE: </b>' + layer.feature.properties.InfoboxTitle + '<br>'
+ '<b>STATION:</b>' + layer.feature.properties.Station + '<br>'
+ '<b>START: </b>' + layer.feature.properties.StartDateTime + '<br>'
+ '<b>END: </b>' + layer.feature.properties.EndDateTime + '<br>';
layer.bindPopup(popupText);
layer._leaflet_id = feature.properties.LayerId;
if (feature.properties.LayerId == "0") { layer0.addLayer(layer); }
else if (feature.properties.LayerId == "1") { layer1.addLayer(layer); }
else if (feature.properties.LayerId == "2") { layer2.addLayer(layer); }
else if (feature.properties.LayerId == "3") { layer3.addLayer(layer); }
else if (feature.properties.LayerId == "4") { layer4.addLayer(layer); }
else if (feature.properties.LayerId == "5") { layer5.addLayer(layer); }
else if (feature.properties.LayerId == "6") { layer6.addLayer(layer); }
else if (feature.properties.LayerId == "7") { layer7.addLayer(layer); }
else if (feature.properties.LayerId == "8") { layer8.addLayer(layer); }
else if (feature.properties.LayerId == "9") { layer9.addLayer(layer); }
else if (feature.properties.LayerId == "10") { layer10.addLayer(layer); }
else if (feature.properties.LayerId == "11") { layer11.addLayer(layer); }
},
filter: function (feature, layer) {
return (
feature.properties.Identifier === WarnFilter.tornado ||
feature.properties.Identifier === WarnFilter.svr ||
feature.properties.Identifier === WarnFilter.flood
)
},
interactive: true
});
}).fail(function (err) { console.log('createWarningsErr: ', err); })
};
//**********//
function isActive(layer) {
if (layer == "TOR") { return tornadoActive; }
else if (layer == "SVR") { return tstrmActive; }
else if (layer == "FFW") { return ffwActive; }
}
var isAnyActive = function () { return tornadoActive || svrActive || ffwActive; }
var toggleLayer = function (layer, checkState) {
switch (layer) {
case "TOR": (checkState) ? WarnFilter.tornado = 'TOR' : WarnFilter.tornado = null; tornadoActive = !tornadoActive;
break;
case "SVR": (checkState) ? WarnFilter.svr = 'SVR' : WarnFilter.svr = null; svrActive = !svrActive;
break;
case "FFW": (checkState) ? WarnFilter.flood = 'FFW' : WarnFilter.flood = null; ffwActive = !ffwActive;
break;
default:
if (checkState) {
for (key in WarnFilter) {
if (WarnFilter.hasOwnProperty(key)) {
debugger
WarnFilter[key] = (key.toString()).toUpperCase();
}
}
}
//set all values in filter themselves to show
else {
for (key in WarnFilter) {
if (WarnFilter.hasOwnProperty(key)) {
WarnFilter[key] = null;
}
}
}
break;
}
showHide(layer, checkState);
}
//**********//
var showHide = function (layer, checkState) {
rerender();
if (isAnyActive() && checkState) {
warnConditionsLayersGroup[GlobalMapLoop.getLoopIndex()].addTo(getMap());
}
else {
warnConditionsLayersGroup[GlobalMapLoop.getLoopIndex()].removeLayer(getMap());
}
}
var loop = function (currentIndex, pastIndex) {
console.log("got to warn loop", currentIndex, pastIndex, isAnyActive())
if (isAnyActive()) {
getMap().removeLayer(warnConditionsLayersGroup[pastIndex]);
getMap().addLayer(warnConditionsLayersGroup[currentIndex]);
}
}
var rerender = (function () {
init();
})
return {
init: init,
toggleLayer: toggleLayer,
loop: loop,
rerender: rerender
};
})();
I have this list and want to sum value and remove duplicates in List
1 - check of productName
2 - sum NumberOfItems if productName equals
For Example :
"Orders":[
{
"productName":"Apple",
"NumberOfItems":"5"
},
{
"productName":"Orange",
"NumberOfItems":"2"
},
{
"productName":"Egg",
"NumberOfItems":"5"
},
{
"productName":"Apple",
"NumberOfItems":"3"
},
{
"productName":"Orange",
"NumberOfItems":"4"
},
{
"productName":"Egg",
"NumberOfItems":"9"
},
]
The result I need look like this result : (Sum Depend on productName)
"Orders":[
{
"productName":"Apple",
"NumberOfItems":"8"
},
{
"productName":"Orange",
"NumberOfItems":"6"
},
{
"productName":"Egg",
"NumberOfItems":"14"
},
]
final orders = data["Orders"] as List;
final mapped = orders.fold<Map<String, Map<String, dynamic>>>({}, (p, v) {
final name = v["productName"];
if (p.containsKey(name)) {
p[name]["NumberOfItems"] += int.parse(v["NumberOfItems"]);
} else {
p[name] = {
...v,
"NumberOfItems": int.parse(v["NumberOfItems"])
};
}
return p;
});
final newData = {
...data,
"Orders": mapped.values,
};
print(newData);
Result is:
{Orders: ({productName: Apple, NumberOfItems: 8}, {productName: Orange, NumberOfItems: 6}, {productName: Egg, NumberOfItems: 14})}
Notice: This code has 2 loop which means slower.
Igor Kharakhordin answered smarter one, but may be difficult for those who ask this question.(since he is doing two things at once.) Basically I am doing same thing.
String string = await rootBundle.loadString("asset/data/Orders.json");
Map orders = jsonDecode(string);
List orderList = orders["Orders"];
Map<String,int> sums = {};
for(int i = 0 ; i < orderList.length; i++){
dynamic item = orderList[i];
if(sums.containsKey(item["productName"])){
sums[item["productName"]] += int.parse(item["NumberOfItems"]);
}
else{
sums[item["productName"]] = int.parse(item["NumberOfItems"]);
}
}
List sumList = [];
sums.forEach((key,value)=>
sumList.add({
"productName":key,
"NumberOfItems":value.toString()
})
);
Map result = {
"Orders":sumList
};
print(jsonEncode(result));
Result
{
"Orders": [
{
"productName": "Apple",
"NumberOfItems": "8"
},
{
"productName": "Orange",
"NumberOfItems": "6"
},
{
"productName": "Egg",
"NumberOfItems": "14"
}
]
}