Iterate with index - list

Is there a way to iterate through a list having access to the object and the index?
For example, I have:
Row(
children: items.map((item) {
int index = items.indexOf(item);
return widget(index);
}).toList()),
I would like to have something that gives me directly the item and its index, so that I don't have to evaluate the index with:
int index = items.indexOf(item);
but write only:
Row(
children: items.functionThatIWant((index,item) {
return widget(index);
}).toList()),

If you have _current as your index, then you can get the item at the desired index by doing
items.elementAt(_current);
That is assuming that items is indeed a List<T>

Related

How to make a list with a for in Dart

This is my first question so I'm sorry if it's not well formatted.
So, I have this object called book with the property "rating," which is an int of the number of stars. My idea is to show in a row said rating as icons and I thought I'd do it with a spread operator and a for.
I don't know if it's possible because I don't find any documentation about it or if the syntax is wrong because it expects and identifier and a ')' See issue. I would appreciate help with this.
child: Row(
children: [...(for (var i = 0; i < book.rating; i++) => Icon(Icons.star))],
),
You can also made by using List generate.
Row(
children: List<Widget>.generate(book.rating, (idx) => Icon(Icons.star)),
);
There are syntax errors. Remove =>, () from start, ...:
child: Row(
children: [for (var i = 0; i < book.rating; i++) Icon(Icons.star)],
),

How do I loop and render through a list of predefined widgets?

So I have a list of predefined choices that I defined below
final List<DropdownMenuItem> grades = <DropdownMenuItem>[
DropdownMenuItem(value: "Highschool", child: Text('Highschool')),
DropdownMenuItem(value: "Senior High", child: Text('Senior High')),
DropdownMenuItem(value: "College", child: Text('College'))];
And what I want to do is traverse through the list and put it under the drop down menu
Form(
child: DropdownButtonHideUnderline(
child: ButtonTheme(
alignedDropdown: true,
child: DropdownButton<String>(
value: defState,
onChanged: (String? newValue) {
setState(() {
defState = newValue!;
});
},
items: grades.map((items) => return items),
hint: Text("Grade"),
),
)),
)
But it's giving me these two errors
The argument type 'Iterable<DropdownMenuItem<dynamic>>' can't be assigned to the parameter type 'List<DropdownMenuItem<String>>?'.
Unexpected text 'return'.
Try removing the text.
Is there a way to iterate the list so I can just immediately return?
A few things:
First, arrow functions don't need the return keyword. For example, the following 2 functions are equivalent:
grades.map((_) => 'hello')
grades.map((_) {
return 'hello';
})
Secondly, the error message says: "you gave me an Iterable<DropdownMenuItem<dynamic>>, but I need a List<DropdownMenuItem<String>>".
You're creating a DropdownButton<String>, which takes a List<DropdownMenuItem<String>> as its items parameter, but you pass in grades.map( ... ).
map() is defined in Iterable, and has the following signature:
Iterable<T> map<T>(T f(E e))
This is a little bit opaque, but crucially, it returns an Iterable<T>, where T is the return type of the function you pass in, for example:
List<int> ints = [1, 2, 3];
Iterable<String> strings = ints.map((i) => i.toString());
To fix your problem, you should do the following:
instead of having a final field with widgets inside, make it a function. You should avoid caching widgets like this (unless they are const) as it interferes with hot-reload. Importantly, the function should also specify the type of DropdownMenuItem it returns:
List<DropdownMenuItem<String>> get grades => [
DropdownMenuItem<String>(...),
...
]
Your map function is invalid, but if you remove the return keyword, it would be (items) => items, which is the identity function (i.e. it does nothing). You can remove this and it will work.
Alternatively, if you want to call some function, you then need to call toList() on the result, since items expects a list:
items: grades,
// or
items: grades.map((grade) => ...).toList(),
Change the type of grades list to List<DropdownMenuItem<String>>:
final List<DropdownMenuItem<String>> grades = [
DropdownMenuItem(value: "Highschool", child: Text('Highschool')),
DropdownMenuItem(value: "Senior High", child: Text('Senior High')),
DropdownMenuItem(value: "College", child: Text('College'))
];
And just use grades instead of a map:
DropdownButton<String>(
value: defState,
onChanged: (String? newValue) {
setState(() {
defState = newValue!;
});
},
items: grades,
hint: Text("Grade"),
),

Using Animated Switcher, which are stored in a List

I want to have a Scaffold, which contains a variable amount of Elements in a ListView. The Elements are all equal, just a few values are different. So I made a Scaffold for those Elements and want to store them in a growable List. My Problem is, that the AnimatedSwitcher doesn't work anymore when I retrieve it from the List.
bool Boolean = false; <br/>
List<Widget> widgets = [ AnimatedSwitcher(<br/>duration: Duration(seconds: 2), <br/>child: Boolean ? childrenOne : childrenTwo) ]
body: ListView( <br/>
children: widgets
),

Display items in a list containing a specific name - flutter

In this list, I want to display out all the items that contains this specific name.
My list items: ['US', 'SG', 'US']
print(list.contains("US"));
Using .contains() returns me a true or false but it doesn’t return me the list of strings that contains that. I want to only extract out the items that has 'US' from the list. In this case, there's 2 of it. Please help!
You can try doing it the following way -
List<String> myList = ['US', 'SG', 'US'];
print(myList.where((item) => item.contains("US")));
You can also display it directly inside a Text widget in the following way -
Text(
myList.where((item) => item.contains("US")).join(" "),
//The join function joins the elements of the Iterable into a single string with the separator provided as an argument.
),
Hope this helps!
UPDATE:
To display each of the word separately as a list you can display them inside a Column in the following way -
Column(
children: myList.map((value) {
if(value.contains("US")){
return Text(value,);
} else {
return Container();
//Return an empty Container for non-matching case
}
}).toList(),
)
The same thing can be used inside a ListView instead of Column if you want it to be scrollable.
Something like this?
var myList = ['US', 'SG', 'US'];
myList.forEach((w){
if(w == "US")
print(w);
});
To show:
class SO extends StatelessWidget {
var myList = ['US', 'SG', 'US'];
#override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisSize: MainAxisSize.min,
children: myList.where((w) => w == "US").map((w) => Text(w)).toList(),
),
);
}
}
or for a single line display use, Text instead of Column widget mentioned above
Text(myList.where((w) => w.contains("US")).join(" "))
If you are using "list.contains". It will only show the list exist or not , If you want to print the value you have to use follow :
var fruits = [‘banana’, ‘pineapple’, ‘watermelon’];fruits.forEach((fruit) => print(fruit)); // => banana pineapple watermelon
If you want to print just banana then you can use this
var fruits = [‘banana’, ‘pineapple’, ‘watermelon’];fruits.(fruit) => print(fruit[0]); // => banana

Using getFillteredRows in google charts with additional property

I have a row structure like this
c:[
{ v: 'somevalue'},
{ v: 'somevalue'},
{
v: 'somevalue',
link: 'abc.com'
}
]
now I need all the rows which has link property present in 3rd column, is it possible using getFillteredRows function ?
first, to use cell properties correctly, the structure would resemble the following...
c:[
{ v: 'somevalue'},
{ v: 'somevalue'},
{
v: 'somevalue',
p: {
link: 'abc.com'
}
}
]
to get or set the properties, use the following methods...
getProperty(rowIndex, columnIndex, name)
setProperty(rowIndex, columnIndex, name, value)
adding in getFilteredRows (spelling - one L in filter)...
use the test function, to find all the rows which has link property present in 3rd column
var rowsFound = data.getFilteredRows([{
column: 2,
test: function (value, row, column, table) {
return (table.getProperty(row, column, 'link') !== null);
}
}]);