I have a simplified flutter control, think of a row of 'radio' buttons or a menu bar. The parent passes in a list of 'captions' for each button and a callback. The control then hits the callback passing the index of the button tapped. The issue is, the 'buttons' are created dynamically and the quantity may vary by the parent. When I set the callback for the onTap function in GestureDetector, it will always hit the callback with the last value of the parameter (idx) in the loop. So if there are 4 buttons, the doCallback is always called with a 4, no matter which button is tapped. It appears like doCallback is being called with a reference to idx, rather than the value of idx. Is there a way to make each button send it's own index to the callback?
class CtrlRadioSelector extends StatelessWidget {
CtrlRadioSelector({Key? key, required this.captions, required this.onTapItem})
: super(key: key);
final List<String> captions;
final ValueSetter<int> onTapItem;
@override
Widget build(BuildContext context) {
List<Widget> selectorItems = [];
int idx = 0;
for (var caption in captions) {
selectorItems.add(Expanded(
flex: 10,
child: GestureDetector(
onTap: () => doCallback(idx),
child: Text(caption,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 18)))));
idx++;
}
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: selectorItems);
}
void doCallback(int idx) {
onTapItem(idx);
}
}