How to setState inside showModalBottomSheet
I also faced the same problem. Its a small trick, you need to insert StatefulBuilder
in the showModalBottomSheet. I will use a different code to make someone out there understand easily using checkbox now that the answer comes way late.
showModalBottomSheet(
context: context,
isScrollControlled: true,
builder: (BuildContext context) {
mpesachecked =false;
return StatefulBuilder(builder: (BuildContext context, StateSetter mystate) {
return Padding(
padding: const EdgeInsets.fromLTRB(10.0, 70.0, 20.0, 20.0),
child: Column(
children: <Widget>[
Checkbox(
value: mpesachecked,
activeColor: Colors.green,
onChanged: (value) {
mystate(() {
mpesachecked = value;
});
}),
])
));
});
)
NOTE: the new state within the showModalBottomSheet is mystate
The problem here is that the BottomSheet
you are creating is not part of your StatefulWidget
. If you only made your widget stateful for the purpose of using setState
inside of showModalBottomSheet
, you can revert that change now.
What you really want to do is set the state inside of your BottomSheet
. You do that by either passing a StatefulWidget
to the builder
or by using a StatefulBuilder
, which I will do for this example for the sake of simplicity:
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return BottomSheet(
onClosing: () {},
builder: (BuildContext context) {
bool b = false;
return StatefulBuilder(
builder: (BuildContext context, setState) => Switch(
onChanged: (bool v) {
setState(() => b = v);
},
value: b,
),
);
},
);
},
);
I also moved the b
value inside the builder
function of the BottomSheet
.
If you want to use the value of b
inside of your original StatefulWidget
as well, you would move it out again and you probably want to call this.setState
as well to also update the other widget (only if you need it to update).