Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flutter checkbox doesn't work

I want to build a checkbox with CheckboxListTile inside this widget dialog but when I tap the checkbox the checked on the checkbox doesn't change.

This is my code:

Future<Null> _showGroupDialog(BuildContext context) async {
    await showDialog(
        context: context,
        builder: (BuildContext dialogContext) =>
            Dialog(child: _buildCheckboxGroups(context)));
}

Widget _buildCheckboxGroups(BuildContext context) {
    List<Widget> childrens = List.generate(_groups.length, (index) {
      return CheckboxListTile(
        title: Text(_groups[index].name),
        value: _groups[index].checked,
        onChanged: (bool val) {
          setState(() {
            _groups[index].checked = val;
          });
        },
      );
    });

    return Container(
        child: Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: childrens,
    ));
}

Btw, the onChange method is invoked when I tap the checkbox. Can anyone solve this?

like image 861
cahyowhy Avatar asked Jul 29 '18 09:07

cahyowhy


1 Answers

class _MyHomePageState extends State<MyHomePage>{

 //<Here you have to set default value for _groups[index].checked to false/true>
 @override
 Widget _buildCheckboxGroups(BuildContext context) {
  List<Widget> childrens = List.generate(_groups.length, (index) {
    return CheckboxListTile(
    title: Text(_groups[index].name),
    value: _groups[index].checked,
    onChanged: (bool val) {
      setState(() {
        _groups[index].checked = val;
      });
    },
  );
});}

Working Example is given below

class _MyHomePageState extends State<MyHomePage> {
 bool flagWarranty=false;
 @override
 Widget build(BuildContext context) {
  return Scaffold(
  appBar: AppBar(title: Text(widget.title)),
  body: new Container(
      padding: new EdgeInsets.all(20.0),
      child: new Form(
        key: this._formKey,
        child: new ListView(
          children: <Widget>[
              new Checkbox(
              value: flagWarranty,
              onChanged: (bool value) {
                setState((
                    ) {
                  flagWarranty=value;
                });
              },
            )
       ],),)));
 }}
like image 137
lavish Avatar answered Oct 20 '22 04:10

lavish