在 flutter 中使用图标按钮的单选按钮样式

Dar*_*ioS 2 android ios dart flutter

我想使用 Flutter (Dart) 中的图标创建一个单选按钮样式的投票系统,如下所示: 投票图标

这个概念很简单:页面将显示一部电影,然后用户可以使用上面的图标按钮对该电影进行投票。进行投票后,图标会变为红色,并且电影会添加到数组中。

我正在努力解决的棘手部分是:

  1. 选择后更改图标的颜色
  2. 确保其他图标保持黑色
  3. 如果用户选择不同的选项,则将其他图标更改回黑色

提前致谢!

Mar*_*ink 5

结果

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;
          },
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)