在flutter中创建一行五个按钮,这样一次只能按下一个按钮,当按钮被按下时,它的颜色应该从白色变为红色,文本颜色也是如此,还重构了按钮控件。
我用过材料按钮,但问题是,当只按一个按钮时,所有按钮的重置都会自动按下,而且不会再次取消点击
代码
class SizeButton extends StatefulWidget {
String text;
bool small = false;
bool medium = false;
bool large = false;
bool extraLarge = false;
SizeButton({Key? key, required this.text}) : super(key: key);
@override
State<SizeButton> createState() => SizeButtonState();
}
class SizeButtonState extends State<SizeButton> {
bool isClicked = false;
void selectSize(String size) {
setState(() {
if (size == 'S') {
widget.small = !widget.small;
widget.medium = false;
widget.large = false;
widget.extraLarge = false;
} else if (size == 'M') {
widget.small = false;
widget.medium = !widget.medium;
widget.large = false;
widget.extraLarge = false;
} else if (size == 'L') {
widget.small = false;
widget.medium = false;
widget.large = !widget.large;
widget.extraLarge = false;
} else if (size == 'XL') {
widget.small = false;
widget.medium = false;
widget.large = false;
widget.extraLarge= !widget.extraLarge;
}
isClicked = widget.small || widget.medium || widget.large || widget.extraLarge;
});
}
@override
Widget build(BuildContext context) {
return InkWell(
child: Container(
width: 40,
height: 40,
decoration: BoxDecoration(
border:Border.all(color: Colors.grey, width: 1.w),
shape: BoxShape.circle,
color: isClicked ? Colors.pink : Colors.white,
),
child: Center(
child: Text(widget.text,
style: TextStyle(
fontSize: 20.sp,
color: isClicked ? Colors.white : Colors.black,
),
),
),
),
onTap: () {
selectSize(widget.text);
},
);
}
}
1条答案
按热度按时间kcwpcxri1#
创建dataModel类
放置微件类,如下所示
如果要选择列表中单个项目,请更改ontap方法