Pass the position of a ListView Element's CheckBox to onChanged callback in Flutter
371
Solution: Anonymous Functions
In Dart, you can create one line functions and you can pass parameters to them. Hope this works!
int numberLines = 50;
List<bool> checkBoxValues = [];
int i = 0;
while(i < numberLines)
{
checkBoxValues.add(false);
i++;
}
void medCheckedChanged(bool value) => setState(() => checkBoxValues[position] = value);
ListView.builder
(
itemCount: numberLines,
itemBuilder: (context, position)
{
return Column
(
children: <Widget>
[
Container
(
height: resLayout.getScreenHeightPercentage(context, 6),
width: resLayout.getScreenHeightPercentage(context, 14),
alignment: Alignment(0, 0),
child: Checkbox
(
value: checkBoxValues[position],
onChanged: (value) => medCheckedChanged(value), //pass to medCheckedChanged() the position
),
)
]
),
}
)
Author by
sal65535
Updated on December 04, 2022Comments
-
sal65535 over 1 year
I wrote the peace of code below:
int numberLines = 50; List<bool> checkBoxValues = []; int i = 0; while(i < numberLines) { checkBoxValues.add(false); i++; } void medCheckedChanged(bool value) => setState(() => checkBoxValues[position] = value); ListView.builder ( itemCount: numberLines, itemBuilder: (context, position) { return Column ( children: <Widget> [ Container ( height: resLayout.getScreenHeightPercentage(context, 6), width: resLayout.getScreenHeightPercentage(context, 14), alignment: Alignment(0, 0), child: Checkbox ( value: checkBoxValues[position], onChanged: medCheckedChanged, //pass to medCheckedChanged() the position ), ) ] ), } )
As you can see, I need to use the position variable in my
medCheckedChanged(bool value)
callback, but I can't pass it as a parameter.... Is there any other way to do it?Thanks in advance and Keep Coding with <3
-
Golden Lion almost 3 yearsA better way is to pass the object associated with the list view contents. You can then reposition your list view to the selected object.
-
Golden Lion almost 3 yearsvoid medCheckedChanged(bool value) => setState(() => checkBoxValues[position] = value); this code looks incorrect. position should be throwing an error since it was not passed to the void function
-
-
sal65535 over 4 yearsThanks for your answer