效果演示


页面

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,
    );
  }
}

裸阳
8 声望1 粉丝