接收组件列表,可指定边线、圆角、颜色等属性。根据具体逻辑,可以实现多个按钮单选或多选的需求。
ToggleButtons单选切换
【children】: 子组件集 【List
【borderWidth】: 边线宽 【double】
【borderRadius】: 圆角 【BorderRadius】
【isSelected】: 是否选中集 【List
【onPressed】: 点击事件 【Function(int)】
import 'package:flutter/material.dart';
class CustomToggleButtons extends StatefulWidget {
@override
_CustomToggleButtonsState createState() => _CustomToggleButtonsState();
}
class _CustomToggleButtonsState extends State<CustomToggleButtons> {
var _isSelected = [true, false, false];
@override
Widget build(BuildContext context) {
return ToggleButtons(
children: <Widget>[
Icon(Icons.skip_previous),
Icon(Icons.pause),
Icon(Icons.skip_next),
],
borderWidth: 1,
borderRadius: BorderRadius.circular(10),
isSelected: _isSelected,
onPressed: (value) => setState(() {
_isSelected = _isSelected.map((e) => false).toList();
_isSelected[value] = true;
}),
);
}
}
ToggleButtons颜色属性
【borderColor】: 边线色 【Color】
【selectedBorderColor】: 选中边线色 【Color】
【selectedColor】: 选中时组件色 【Color】
【fillColor】: 选中时填充色 【Color】
【splashColor】: 水波纹色 【Color】
import 'package:flutter/material.dart';
class ColorToggleButtons extends StatefulWidget {
@override
_ColorToggleButtonsState createState() => _ColorToggleButtonsState();
}
class _ColorToggleButtonsState extends State<ColorToggleButtons> {
var _isSelected = [true, false, false];
@override
Widget build(BuildContext context) {
return ToggleButtons(
children: <Widget>[
Icon(Icons.skip_previous),
Icon(Icons.pause),
Icon(Icons.skip_next),
],
borderWidth: 1,
borderColor: Colors.orangeAccent,
selectedBorderColor: Colors.blue,
splashColor: Colors.purple.withAlpha(66),
borderRadius: BorderRadius.circular(10),
selectedColor: Colors.red,
fillColor: Colors.green.withAlpha(11),
isSelected: _isSelected,
onPressed: (value) => setState(() {
_isSelected = _isSelected.map((e) => false).toList();
_isSelected[value] = true;
}),
);
}
}
ToggleButtons多选切换
可以控制状态转化的逻辑来形成不同的效果。<br />![24.gif](https://cdn.nlark.com/yuque/0/2020/gif/326147/1589428281066-f31cdf9c-6fa3-4747-875a-b536c17b8fda.gif#align=left&display=inline&height=103&margin=%5Bobject%20Object%5D&name=24.gif&originHeight=103&originWidth=403&size=101350&status=done&style=none&width=403)
import 'package:flutter/material.dart';
class ProToggleButtons extends StatefulWidget {
@override
_ProToggleButtonsState createState() => _ProToggleButtonsState();
}
class _ProToggleButtonsState extends State<ProToggleButtons> {
var _isSelected = [false, false, false];
@override
Widget build(BuildContext context) {
return ToggleButtons(
children: <Widget>[
Icon(Icons.skip_previous),
Icon(Icons.pause),
Icon(Icons.skip_next),
],
borderWidth: 1,
borderColor: Colors.blue,
selectedBorderColor: Colors.orangeAccent,
splashColor: Colors.purple.withAlpha(66),
borderRadius: BorderRadius.circular(10),
selectedColor: Colors.red,
fillColor: Colors.green.withAlpha(11),
isSelected: _isSelected,
onPressed: (value) => setState(() {
_isSelected[value] = !_isSelected[value];
}),
);
}
}