我的自定义 CheckBox 的逻辑与材质的默认 CheckBox 不同,我该怎么解决这个问题?
这里我有一列有两个Material的Checkbox,它们背后的逻辑是:一旦选中一个,另一个就会自动取消选中
Column(
children: [
SizedBox(
width: screenSize.width * .38,
height: screenSize.height * .07,
child: CardBox(
shadowSize: 2,
customRadius: const [10, 10],
boxContent: Row(
children: [
Transform.scale(
scale: 1.3,
child: Checkbox(
value: bool1Selected,
activeColor: widget.color,
checkColor: widget.color,
onChanged: (newBool) {
setState(() {
bool2Selected= false;
bool1Selected= newBool;
});
},
),
),
const SizedBox(
width: 5,
height: 1,
),
Text('Spain',
style: const TextStyle(
fontSize: 35,
),
))
],
),
),
),
SizedBox(
width: screenSize.width * .38,
height: screenSize.height * .02,
),
SizedBox(
width: screenSize.width * .38,
height: screenSize.height * .07,
child: CardBox(
shadowSize: 2,
customRadius: const [10, 10],
boxContent: Row(
children: [
Transform.scale(
scale: 1.3,
child: Checkbox(
value: bool2Selected,
activeColor: widget.color,
checkColor: widget.color,
onChanged: (newBool) {
setState(() {
bool1Selected = false;
bool2Selected = newBool;
});
},
),
),
const SizedBox(
width: 5,
height: 1,
),
Text(
'EUA',
style: const TextStyle(
fontSize: 35,
),
),
),
],
),
),
),
],
),
使用上面的代码,它可以正常工作,但是我制作了一个自定义 CheckBbox 来更好地满足我的目的,但是一旦我单击一个 CheckBox,另一个复选框就不会被选中。请按照以下代码操作:
class _CustomCheckboxState extends State<CustomCheckbox> {
Color borderColor = ThemeColors.cardHighlight;
bool isChecked = false;
@override
void initState() {
super.initState();
isChecked = widget.isChecked;
}
@override
Widget build(BuildContext context) {
var screenSize = MediaQuery.of(context).size;
return InkWell(
child: Container(
width: screenSize.width * .35,
height: screenSize.height * .07,
decoration: BoxDecoration(
color: ThemeColors.cardHighlight,
boxShadow: kElevationToShadow[3],
borderRadius: const BorderRadius.all(Radius.circular(10)),
border: Border.all(
width: 6,
strokeAlign: BorderSide.strokeAlignInside,
color: isChecked ? borderColor = widget.borderColor : borderColor = ThemeColors.cardHighlight,
),
),
child: Center(
child: Text(
widget.text,
style: TextStyle(fontSize: 35),
),
),
),
onTap: () {
setState(
() {
isChecked = !isChecked;
widget.onChange(isChecked);
},
);
},
);
}
}
我尝试分析Material CheckBox源代码,但是里面有很多东西比如状态管理我仍在尝试在flutter中学习,有人可以告诉我如何解决这个问题吗?
即使您将正确的更新值传递给 CustomCheckbox 并将其设置在
initState
内,它仍按预期工作。 initState 在创建小部件时只会调用一次,其余内容从状态类更新。
为了更新状态类,您可以覆盖
didUpdateWidget
@override
void didUpdateWidget(covariant CustomCheckbox oldWidget) {
super.didUpdateWidget(oldWidget);
isChecked = widget.isChecked;
// setState(() {});
}
另外,我更喜欢根据您当前的代码片段使用无状态小部件。