Set order by random in flutter dart - flutter

I want to show my category products order by random. So trying to change it but it doesn’t work.
Only date, menu order, popularity, rating these sort method working. Is there any way to set orderby random work in dart?
> #observable
Map<String, dynamic> _sort = {
'key': 'product_list_default',
'query': {
'order': 'desc',
'orderby': 'date', //want to change to random
};

this is not hard..
If your categories are in a List
e.g
List categories = [category1, category2, category3]
You can use a method like this
//first get a random index that will exist in the category list (in this case 'List categories')
Random random = new Random();
int randomNumber = random.nextInt(categories.length); //from index 0 to the last index
//now to use the random number to select a category
var randomCategory = categories[randomNumber]

Related

how to sort Map<String,double> based on its value in flutter

I have a map with String,double and I want to sort this map based on its value and want to take only first 4 key value pair..like following
Map<String,dynamic> mymap={
'A':2000,
'B':8000,
'C':300,
'D':3890,
'E':8030,
'F':300,
'G':900,
};
and I want to convert into following
Map<String,dynamic> resultmap={
'E':8030,
'B':8000,
'D':3890,
'A':2000,
'Others':1500,
};
To sort a map in descending order by value, you can use something like below (look here for more info).
var numbers = {'one': 1, 'two': 2, 'three': 3, 'four': 4};
print(numbers); // {one: 1, two: 2, three: 3, four: 4}
final sortedValuesDesc = SplayTreeMap<String, dynamic>.from(
numbers, (keys1, keys2) => numbers[keys2]!.compareTo(numbers[keys1]!));
print(sortedValuesDesc); // {four: 4, three: 3, two: 2, one: 1}
To get the sum of the rest of the values, there are some different options to choose from. I found this approach here on Stack Overflow:
final sum = numbers
.values
.skip(4)
.reduce((value, element) => value + element);
What remains is to make sure the summed elements are removed and the above sum is added to the map along with your desired key.
Let me know if this worked for you. :-)
You can do this in several steps.
First declare your map.
Map<String,dynamic> mymap={
'A':2000,
'B':8000,
'C':300,
'D':3890,
'E':8030,
'F':300,
'G':900,
};
Then, sorting the declared map in descending order by using this code.
var sortedList = mymap.entries.toList()..sort((b,a)=>a.value.compareTo(b.value));
Then, create a new map and add the sorted list as entries inside the new map.
Map newMap={};
newMap.addEntries(mapList);
Now, find other number's sum using this code.
int otherNumbersSum = newMap.values.skip(4).reduce((value, element) => value + element);
Finally, create a new map and add entries in that map by checking that either they are three digits or four digits and at last adding the sum which we got in the last step.
Map finalMap ={};
for(var a in newMap.entries){
if(a.value>999){
finalMap[a.key] = a.value;
}
}
finalMap["Others"] = otherNumbersSum;
You will get result like this.
finalMap ={
'E':8030,
'B':8000,
'D':3890,
'A':2000,
'Others':1500,
};
Hope it will help :)

How can I gather and show results of a survey made with survey_kit package in Flutter?

I am struggling in retrieving the results obtained from a survey built with survey_kit package. A SurveyResult object is supposed to contain a list of StepResults and the FinishReason. The StepResult contains a list of QuestionResults. I cannot access the StepResult in anyway.
Example proposed in the documentation:
SurveyKit
(
onResult: (SurveyResult result) {
//Read finish reason from result (result.finishReason)
//and evaluate the results }
)
I already tried to tap something like result.stepResult but no variable was suggested.
I'm not sure if its the best approach but after looking into SurveyKit I've found that the SurveyResult class holds a list of StepResult and each of them holds a list of QuestionResult which in turn holds a value field called valueIdentifier.
so you can Iterate over them and extract the values. but first, you need to ensure that all of your answers have value. for example:
answerFormat: const SingleChoiceAnswerFormat(
textChoices: [
TextChoice(text: 'option 1', value: '10'),
TextChoice(text: 'option 2', value: '-2'),
]
),
Then after you did that iterate over them like that:
onResult: (SurveyResult result) {
int score = 0;
for (var stepResult in result.results) {
for (var questionResultin stepResult.results) {
score += int.tryParse(questionResult.valueIdentifier ?? "0") ?? 0;
}
}
print("final Score is $score");
/* call a new widget to show the results*/
},
As you can see I use two null checks when adding a question value to the score.
The first one is because the value is of type "String?" (and not "String") and the second one is because the String value might be non-numeric.
Of course, after you have calculated the results you can show the result on a new screen with Navigator.

How to retrieve values from a Map within a List Flutter?

I have a list that contains single values and maps from which I want to filter data.
E.g.
List _filters = [];
String _minPrice = '';
String _maxPrice = '';
//_filters = ['Car', 'House', 6, {'minPrice': '5000', 'maxPrice': '6000'}]
I want to be able to access the minPrice and the maxPrice so that I can use them but I'm not sure how to access them.
String get minPrice {
return _minPrice;
}
String get maxPrice {
return _maxPrice;
}
The list is dynamic and at no particular order.
The use case is where a user is filtering data and one of the filters is
{'minPrice' : '5000', 'maxPrice': '6000'}
You can use list.whereType(), as per this example in order to access by type. https://coflutter.com/dart-filter-items-in-a-list-by-type/
This is complete code to get the property,
List _filters = ['Car', 'House', 6, {'minPrice': '5000', 'maxPrice': '6000'}];
final iterableMap = _filters.whereType<Map>().first;
print(iterableMap['minPrice']);
If you want to access all the maps then you can use following :
// this will return iterable
final iterableMap = _filters.whereType<Map>();
if (!iterableMap.moveNext()) {
final map = iterableMap.current();
}

Get index of list of map from map

How do you get index of list of maps from a map. I tried to use indexOf which works but by the time the position of values are mixed up then it returns -1.
UPDATE: It actually doesn't work even in right order
List<Map<String, dynamic>> list = [{'id':1, 'name':'a'}, {'id':2, 'name':'b'}];
Map<String, dynamic> item = {'name':'a','id':1}; //<- position name and id are in different places
print(list.indexOf(item)); // so it return -1
The best way would be to get index of list where item contains same id ... if you know what I mean... How to do it?
You can use indexWhere instead indexOf.
Map<String, dynamic> item = {'name':'a','id':1};
print(list.indexWhere((i) => i['id'] == item['id'])); // prints 0
Map<String, dynamic> item = {'name':'b','id':2};
print(list.indexWhere((i) => i['id'] == item['id'])); // prints 1

How to dynamically count totals of records with a certain value?

I'm looking to create a count of my 'trolleys' field which is dynamic. This should count the number of trolleys on any given day by the type (e.g. a,b,c). However, I don't want to create a static column which only counts by the type (A,B,C). However, instead I would require a dynamic count which would count depending on the 'type' as we currently don't know which types will be used as this would change on a day to day basis.
Sample data:
I'm looking to create this in Ireport 5.6.
Proposed Outcome
Any ideas would be excellent :)
You can use HashMap to count your fields, like this.
public Map<String, List<Class>> sortByKey(List<Class> values){
Map<String, List<Class>> map = new HashMap<>();
for(Class value : values){
if(map.containsKey(value.type)){
List<Class> valueByKey = map.get(value.type);
valueByKey.add(value);
}
else{
List<Class> newValues = new ArrayList<>();
newValues.add(value);
map.put(value.type, newValues);
}
}
return map;
}
Code above sort your data by key, which is in your example "type" field. You can then get number of each type by checking the size of the list by the specific key. Example bellow.
List<Class> tmp = map.get("a");
int count = tmp.size();