我的目标是在点击相邻的小部件时改变复选框的状态。我试图创建一个有状态的函数,但不幸的是我的代码不起作用。
下面是函数-
void _changeFlagCheckBox(bool? value){
setState(() {
MyCheckBoxCountry.isChecked = value!;
});
}
Inkwell -当你点击它时,它应该会改变myCheckBoxCountry的状态。
child: ListView.builder(
itemCount: city.length,
shrinkWrap: true
itemBuilder: (BuildContext context, int index) {
return InkWell(
onTap: () {
print(city[index]);
_changeFlagCheckBox;
},
child: Container(
margin: const EdgeInsets.only(top: 15),
child:Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children:[
Row(
children:[
SizeBox(width: 10,),
Text(city[index], style: TextStyle(color: ConfigColor.white, fontWeight: FontWeight.w500, fontSize: 15),)
],
),
MyCheckBoxCountry()
],
)
),
);
},
),
我的复选框国家-
class MyCheckBoxCountry extends StatefulWidget {
static bool isChecked = false;
@override
_MyCheckBoxState createState() => _MyCheckBoxState();
}
class _MyCheckBoxState extends State<MyCheckBoxCountry> {
@override
Widget build(BuildContext context) {
return Theme(
data: Theme.of(context).copyWith(
unselectedWidgetColor: ConfigColor.grey,
),
child: Checkbox(
activeColor: ConfigColor.green,
checkColor: ConfigColor.background,
value: MyCheckBoxCountry.isChecked,
shape: CircleBorder(),
onChanged: (bool? value) {
setState(() {
MyCheckBoxCountry.isChecked = value!;
});
},
),
);
}
}
2条答案
按热度按时间rhfm7lfc1#
First of all you're not sending any value in your
_changeFlagCheckBox
function in your Inkwell so how is it supposed to change :but to understand why didn't you get an error like that, well that's because you made the bool value nullable in your
_changeFlagCheckBox
function:Though even then you are not using your
isChecked
value in yourMyCheckBoxCountry
class anywhere :Should have been :
bwntbbo32#
我想因为它是另一个有状态的小部件类,所以它不能识别setState。从父小部件调用子小部件可以解决这个问题。