效果演示

页面
class _TagsState extends State<Tags> {
final int _tagsNum = 8;
late List<bool> _selections;
@override
void initState() {
super.initState();
_selections = List.generate(_tagsNum, (_) => false);
_selections[0] = true;
}
@override
Widget build(BuildContext context) {
return Wrap(
children: <Widget>[
...List.generate(
_tagsNum,
(index) => SelectableButton(
style: TextButton.styleFrom(
foregroundColor: _selections[index] ? Colors.amberAccent : null,
backgroundColor: _selections[index] ? Colors.blueAccent : null,
),
onPressed: () {
setState(() {
for (int i = 0; i < _selections.length; i++) {
_selections[i] = false;
}
_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,
);
}
}