共计 1195 个字符,预计需要花费 3 分钟才能阅读完成。
成果演示
页面
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,
);
}
}
正文完