How to loop through two lists at the same time - Flutter - 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

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 add values of a specific key in a map in a list in dart?

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'];
}

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...

Dart multiple function calls/set variables all on one line

I need to clear some Lists at the start of a function otherwise they just get larger and larger with an add method, so I can either use = [] or .clear() to achieve this, but the formatting puts them all on separate lines like this:
listone.clear();
listtwo.clear();
three.clear();
listfour.clear();
listfive.clear();
listsix.clear();
I want to do something like this but it won't allow it:
listone.clear(), listtwo.clear(), three.clear(), listfour.clear(), listfive.clear(), listsix.clear();
or
listone = [], listtwo = [], three = [], listfour = [], listfive = [], listsix = [];
How do I set multiple variables that have already been declared all on the same single line?
The easiest way to make complex things fit in less space is to use a helper method.
clearAll(Iterable<List<Object>> lists) {
for (var list in lists) list.clear();
}
then you just write:
clearAll([listone, listtwo, three, listfour, listfive, listsix]);
You can inline the helper function
for (var l in [listone, listtwo, three, listfour, listfive, listsix]) l.clear();
but it probably won't fit on one line anyway.
If you are setting variables, and you set the variables to the same value, then you can do multiple assignments as a single expression:
listone = listtwo = three = listfour = listfive = listsix = [];
Not really recommended for lists because then all variables will point to the same list object. It works better when assinging null or another immutable value.
It's not particularly readable either.
There is no simple way in Dart to execute multiple expressions in a single statement without some helper.
You could declare:
void do6(void v1, void v2, void v3, void v4, void v5, void v6) {}
...
do6(listone.clear(), listtwo.clear(), three.clear(),
listfour.clear(), listfive.clear(), listsix.clear());
but you will likely find that will be formatted on more than one line as well
Alternatively, just use a list literal instead of a function parameter list to allow multiple expressions:
[listone.clear(), listtwo.clear(), three.clear(),
listfour.clear(), listfive.clear(), listsix.clear()];
Same caveats about length and formatting, and it's confusion and inefficient that the list is created and then not used.
All in all, please don't try to be clever with formatting. Just write idiomatic code, your readers will have a much easier time understanding it, and the compiler will be more efficient that way.
This is what you can do
void main() {
var listone = [1, 2], listtwo = [1, 1, 1], listthree = [0, 0, 1];
[listone, listtwo, listthree].forEach((l) => l.clear());
print(listone);
print(listtwo);
print(listthree);
}
Check at dartpad
Note: There should be no trailing comma like [x,y,z , /*this one*/] or dartfmt will take it to next line.
EDIT:
Also, if using the same thing in multiple files then
put in a global file
clearList(List list)=>list.clear();
and call something like
[listone, listtwo, listthree].forEach(clearList);

Way to Extract list of elements from Scala list

I have standard list of objects which is used for the some analysis. The analysis generates a list of Strings and i need to look through the standard list of objects and retrieve objects with same name.
case class TestObj(name:String,positions:List[Int],present:Boolean)
val stdLis:List[TestObj]
//analysis generates a list of strings
var generatedLis:List[String]
//list to save objects found in standard list
val lisBuf = new ListBuffer[TestObj]()
//my current way
generatedLis.foreach{i=>
val temp = stdLis.filter(p=>p.name.equalsIgnoreCase(i))
if(temp.size==1){
lisBuf.append(temp(0))
}
}
Is there any other way to achieve this. Like having an custom indexof method that over rides and looks for the name instead of the whole object or something. I have not tried that approach as i am not sure about it.
stdLis.filter(testObj => generatedLis.exists(_.equalsIgnoreCase(testObj.name)))
use filter to filter elements from 'stdLis' per predicate
use exists to check if 'generatedLis' has a value of ....
Don't use mutable containers to filter sequences.
Naive solution:
val lisBuf =
for {
str <- generatedLis
temp = stdLis.filter(_.name.equalsIgnoreCase(str))
if temp.size == 1
} yield temp(0)
if we discard condition temp.size == 1 (i'm not sure it is legal or not):
val lisBuf = stdLis.filter(s => generatedLis.exists(_.equalsIgnoreCase(s.name)))