How to add values of a specific key in a map in a list in dart? - flutter

I am getting a list of maps via an api. Now i want to get the sum of all values of a specific key in the maps. Can anyone help me with that?

A simple for-loop should do the job
Since you have not provided any code, I am making a lot assumptions here, but I hope you get the idea.
List<Map<String, int>> mapList;
// Now add members to list
int sum = 0; // contains the sum of `field` values of all members
for(int i=0; i<mapList.length; i++) {
sum += mapList[i]['field'];
}

Related

ObjectBox Flutter : getAll() with order and limit

My question will seem quite simple, but I'm having a hard time understanding how certain queries work with ObjectBox and Flutter.
I have a List object. I would like to retrieve them all, but display only the first 5, sorted by ascending name.
I find many examples with filter queries in the documentation, but the getAll() does not allow to easily integrate the limit and I find very few examples. I think I'm doing it wrong. What is the best way to do this query ?
final boxListCoins = objectBoxDatabase.store.box<CoinsList>();
// final query = boxListCoins.getAll(); ?
final query = (boxListCoins.query()..order(CoinsList_.coinId, flags: Order.descending)).build();
query.limit = 5;
final coinsList = query.find();
I see that you want to get all your results but you want to display the first 5. So what I would do in your case is:
(1) get all your results(based on your query)
(2) then set another property equal to the top 5:)
** now you have a list of all your entries and you have your top 5 that you can display.
heres how I would code it up!
final boxListCoins = objectBoxDatabase.store.box<CoinsList>();
// final query = boxListCoins.getAll(); ?
final query = (boxListCoins.query()..order(CoinsList_.coinId, flags: Order.descending)).build();
// this is your list of all of the coins!
final coinsList = query.find();
// This is you list of the Top 5
var topFive = [];
if (coinsList.length >= 5) {
// take your top5 here :) also feel free to turn this iterable into what ever you want I just choose to keep it a list :)
topFive = coinsList.take(5).toList();
} else {
// if you length is not greater than 5 then you have your top automatically.
topFive = coinsList;
}
Hope this helps:)
Happy Coding, also I'm a developer #Pieces and if you need a place to store helpful code snippets, like this one, check it out here https://code.pieces.app/

How to loop through two lists at the same time - Flutter

I'm trying to loop through two lists at the same time
For example
List A = ['Chapter 1','Chapter 2','Chapter 3'];
List B = ['Paragraph 1','Paragraph 2','Paragraph 3'];
for(var chapter in A) // This would itreate through only first list (A), How can I iterate through both list
children: [
Text(chapter);
Text(paragraph);
]
I need to iterate through both lists at the same time in "for" loop.
Here is the code:
List A = ['Chapter 1','Chapter 2','Chapter 3'];
List B = ['Paragraph 1','Paragraph 2','Paragraph 3'];
for (int i = 0; i < A.length; i++) {
print ("${A[i]}");
print ("${B[i]}");
}
Let me know if this does not help.
final c = zip([a, b]).map((item) => Foo(item[0], item[1])).toList();
I went along with Randal Schwartz's note about IterableZip. Note that I was not able to find any zip mentioned by Gbenga, and also note that package:collection/iterable_zip.dart is deprecated, you'd need to import simply the collection.dart, like so:
import 'package:collection/collection.dart';
final A = ['Chapter 1','Chapter 2','Chapter 3'];
final B = ['Paragraph 1','Paragraph 2','Paragraph 3'];
for (final pairs in IterableZip([A, B])) {
print(pairs[0]);
print(pairs[1]);
}
Some more notes:
final A and final B variables will be typed List<String> lists, I disadvise dynamic List A.
I have not specified template type for IterableZip, but in some cases (in a complex case where I used it) you may need to explicitly type it like IterableZip<String>, so in the loop you can more conveniently access the members. In this simple case the compiler/interpreter can infer the type easily.
Some other answers in other StackOverflow issues mention quiver, but unless you need it for some other features you don't have to add another extra package dependency to your project. The standard collection package has this IterableZip

Dynamic variable NAME creation in Flutter

I need to dynamically create a List variable depending on the situation.
I have a List of strings. These were created dynamically.
List Categories = [name: 'String 1', name: 'String 2', name: 'String 3']
I need to create a List variable dynamically that can hold EACH string. Don't ask me why, but trust me.
I need something like this:
for(int i = 0 ; i < Categories.length ; i ++)
{
// logic to create a variable of List type and even name it according to the value it is holding:
List String1Var = Categories.[i].name
// or even better :
List $Categories.[i].name = ....
}
so String1Var needs to be named as String1Var - i.e. the name itself has to be dynamic, and the contents too.
Is this possible in flutter?? Or have Google still yet to advance their language so it works for people like me?
Is that the right syntax? How do I dynamically create a variable name?
What you want can be done with the help of Map.
Instead of creating separate variables we are generating dynamic keys and storing the values in it, As Dart has no concept for dynamic variables.
Code:
final Map myCategoryDynamic = {};
for(int i = 0 ; i < Categories.length ; i ++)
{
// logic to create a variable of List type and even name it according to the value it is holding:
myCategoryDynamic['String'+i.toString()+'Var'] = Categories.[i].name;
}
So when we need to check the values - we can check by - myCategoryDynamic[String1Var] myCategoryDynamic[String2Var] and so on...

Joiner - skipDuplicates

I have a situation where I want to remove duplicates from a collection (list) and then join them.
I wanted to make an extension for Joiner, but it is impossible as all constructors are private.
Here's a code snippet of what we did:
Collection<String> tokens = newArrayList();
for (int i = 0; i < numOfFoundTitles; i++) {
if (!tokens.contains(titlesInRange.get(i).titleAsTokens)) {
tokens.add(titlesInRange.get(i).getTitleAsTokens());
}
}
return titleTokensJoiner.join(tokens);
Any suggestions?
I thought about Function / Predicate, but they are not suitable there.
Thanks
Eyal
return titleTokensJoiner.join(ImmutableSet.copyOf(tokens));
Short, sweet, and correct. ImmutableSet preserves the order of the original input, but ignores repeated occurrences of an element after the first occurrence.

Sorting Topscorecollector Results in Lucene.net?

I am doing a search operation by using lucene where i was taking my results by using topscorecollector, but i found that it unable to sort my topscorecollector results. I found it quiet odd to sort that. Can we sort the TopscoreCollector results?
My code looks like this
TopScoreDocCollector collector = TopScoreDocCollector.create(100, true);
indexSearch.Search(andSearchQuery, filter, collector);
ScoreDoc[] hits = collector.TopDocs().scoreDocs;
for (int i = 0; i < hits.Length; i++)
{
int docId = hits[i].doc;
float score = hits[i].score;
Lucene.Net.Documents.Document doc = indexSearch.Doc(docId);
document.Add(doc);
}
Can anybody help me?
Also one more doubt
we can sort the search results like this
Hits hits = IndexSearch.search(searchQuery, filter, sort);
But it is showing that Hits become obselete by Lucene 3.0. so i have opted for TopscoreCollector. But now iam very much confused?
If anyother alternate method for Hits, Please pass that to me...
TopScoreDocCollector will return results sorted by score. To get results sorted on a field you will need to use a method overload that returns TopFieldDocs.
IE: IndexSearcher.Search(query, filter, nResults, sort)
If you dont want to limit the number of results use a very large value for the nResults parameter. If i remember correctly passing Int32.MAX_VALUE will make Lucene generate an exception when initializing its PriorityQueue but Int32.MAX_VALUE-1 is fine.