乐趣区

关于flutter:Flutter-实现简单-TextButton-的单选-Toggle-效果

成果演示


页面

class _TagsState extends State<Tags> {
  final int _tagsNum = 8;
  late List<bool> _selections; // 选中状态 List

  @override
  void initState() {super.initState();

    // 初始化选中状态 List
    _selections = List.generate(_tagsNum, (_) => false);
    // 默认第一个 Tag 是选中状态
    _selections[0] = true;
  }

  @override
  Widget build(BuildContext context) {
    return Wrap(
      children: <Widget>[
        ...List.generate(
          _tagsNum,
          (index) => SelectableButton(
            style: TextButton.styleFrom(
            // null 即 default 色彩
              foregroundColor: _selections[index] ? Colors.amberAccent : null,
              backgroundColor: _selections[index] ? Colors.blueAccent : null,
            ),
            onPressed: () {setState(() {
                // 简略粗犷把所有元素设为 false
                for (int i = 0; i < _selections.length; i++) {_selections[i] = false;
                }
                // 再把本身设 true
                _selections[index] = !_selections[index];
              });
            },
            child: Text("Tag ${index + 1}"),
          ),
        ),
      ],
    );
  }
}

SelectableButton

class SelectableButton extends StatefulWidget {
  const SelectableButton({
    super.key,
    required this.style,
    required this.onPressed,
    required this.child,
  });

  final ButtonStyle? style;
  final Function()? onPressed;
  final Widget child;

  @override
  State<SelectableButton> createState() => _SelectableButtonState();
}

class _SelectableButtonState extends State<SelectableButton> {
  @override
  Widget build(BuildContext context) {
    return TextButton(
      style: widget.style,
      onPressed: widget.onPressed,
      child: widget.child,
    );
  }
}
退出移动版