I build an app with flutter,and I want to create page that allow the user to change the value of "CheckboxListTile" widget in "showModalBottomSheet" widget. The "showModalBottomSheet" widget, should be appear after the user click on button.
Here is my code:
class showModalBottomSheetTester extends StatefulWidget {
const showModalBottomSheetTester({super.key});
@override
State<showModalBottomSheetTester> createState() =>
_showModalBottomSheetTesterState();
}
class _showModalBottomSheetTesterState
extends State<showModalBottomSheetTester> {
bool? _isChecked = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('showModalBottomSheetTester'),
),
body: ElevatedButton(
onPressed: () {
showModalBottomSheet(
context: context,
builder: (BuildContext context) {
return SizedBox(
height: 500,
child: Column(
children: [
const Padding(
padding: EdgeInsets.only(top: 30.0),
child: Text('Head'),
),
CheckboxListTile(
title: const Text('data'),
value: _isChecked,
activeColor: Colors.red,
checkColor: Colors.blue,
tileColor: Colors.green,
subtitle: const Text('data'),
controlAffinity: ListTileControlAffinity.leading,
tristate: true,
onChanged: (bool? newValue) {
setState(() {
_isChecked = newValue;
});
})
],
),
);
});
},
child: const Text('press')),
);
}
}
The UI of this code is greate, but when I click on the checkbox to change the value, there is no change appear at the screen. H ow to resolve this problem?
Within a
showModalSheet, if you callsetState, it won't work. You need to use aStatefulBuilderwithin the sheet instead.So wrap the contents of the modalSheet with a
StatefulBuilder:Here's a complete runnable snippet:
See also
StatefulBuilder (Widget of the Week) - YouTube video by the official Flutter team.
How To Call SetState In Pop-up Alert Dialog - Youtube