'Radio button style using icon buttons in flutter
I want to create a radio button style voting system using icons in Flutter (Dart) which looks like this: vote icons
The concept is simple: The page will display a movie, the user can then vote on that movie using the Icon buttons above. When a vote is made, the icon changes to red and the movie is added to an array.
The tricky part which I am struggling with is:
- Changing the color of the icon after selected
- Making sure that the other icons remain black
- Changing the other icons back to black if the user selects a different choice
Thanks in advance!
Solution 1:[1]
class Example extends StatefulWidget {
@override
_ExampleState createState() => _ExampleState();
}
class _ExampleState extends State<Example> {
int _selected = null;
@override
Widget build(BuildContext context) {
return Row(
children: [
_icon(0, text: "No way", icon: Icons.face),
_icon(1, text: "Maybe", icon: Icons.local_movies),
_icon(2, text: "Looks good", icon: Icons.local_pizza),
_icon(3, text: "Can't wait", icon: Icons.local_fire_department),
],
);
}
Widget _icon(int index, {String text, IconData icon}) {
return Padding(
padding: const EdgeInsets.all(16.0),
child: InkResponse(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
icon,
color: _selected == index ? Colors.red : null,
),
Text(text, style: TextStyle(color: _selected == index ? Colors.red : null)),
],
),
onTap: () => setState(
() {
_selected = index;
},
),
),
);
}
}
Solution 2:[2]
GestureDetector(
onTap:() {},
child: Card(
elevation: 1,
child: Padding(
padding: EdgeInsets.symmetric(
horizontal: 15.w,
vertical: 10,
),
child: Column(
children: [
Icon(
Icons.ac_unit_outlined,
size: 40,
color: _valgroup == 1
? Colors.orange
: Colors.blue,
),
Radio(
activeColor: Colors. orange,
groupValue: _valgroup,
value: 1,
onChanged: (int? value) {
if (value != null) {
setState(() {
_valgroup = value;
});
}
},
),
],
),
),
),
),
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Martin Fink |
Solution 2 | ahmed nader |