I am trying to build a multiple choice Row from a list of Container widgets (wrapped in GestureDetector for onTap). When the user clicks on one of the Container widgets in the Row, that Container widget changes color (to blue) to reflect the user's selection. If the user then taps a different Container widget in the Row, THAT widget changes color to reflect the user's selection, and all others are reset to the initial color (white). Additionally, the user's choice (index?) must be retrievable.
All I have been able to do so far is create a Row of Container widgets that change color on tap, but function independently of one another. That is to say that the user may click on multiple selections, which is bad. I need some advice on how to break through to next level of functionality, where only one container may be selected and the selected value is passed-out.
Cheers, T
//choice button
class ChoiceButton extends StatefulWidget {
final String label;
final bool isPressed;
const ChoiceButton({
Key key,
this.isPressed = false,
this.label,
}) : super(key: key);
@override
_ChoiceButtonState createState() => _ChoiceButtonState();
}
class _ChoiceButtonState extends State<ChoiceButton> {
bool _isPressed;
@override
void initState() {
super.initState();
_isPressed = widget.isPressed;
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
_isPressed = !_isPressed;
});
},
child: Container(
height: 80,
width: 80,
decoration: BoxDecoration(
color: _isPressed ? Colors.blue : Colors.transparent,
border: Border.all(
color: Colors.blue,
width: 80 * 0.05,
),
),
child: Center(
child: Text(
widget.label,
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.bold,
color: _isPressed ? Colors.white : Colors.blue,
),
textAlign: TextAlign.center,
),
),
),
);
}
}
//choice row
class ChoiceRow extends StatefulWidget {
@override
_ChoiceRowState createState() => _ChoiceRowState();
}
class _ChoiceRowState extends State<ChoiceRow> {
bool isPressed = false;
String classChoice = '';
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.start,
children: \[
SizedBox(width: 30),
ChoiceButton(
isPressed: isPressed,
label: 'A',
),
SizedBox(width: 10),
ChoiceButton(
isPressed: isPressed,
label: 'B',
),
SizedBox(width: 10),
ChoiceButton(
isPressed: isPressed,
label: 'C',
),
\],
);
}
}