Patrioticcow
Patrioticcow

Reputation: 27038

Flutter, checkbox state doesn't change, how to?

I have a ListView builder that creates a few ListTitle's with a checkbox inside them.

when I setState on the onChanged on a checkbox, the value doesn't seem to change.

class ProjectPage extends StatefulWidget {
  final project;

  ProjectPage({Key key, this.project}) : super(key: key);

  @override
  _ProjectPageState createState() => new _ProjectPageState();
}

class _ProjectPageState extends State<ProjectPage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Container(
        child: Column(
          children: <Widget>[
            new Expanded(
              child: new ListView.builder(
                itemBuilder: (BuildContext context, int index) => new ItemsItem(item: widget.project.items[index]),
                itemCount: widget.project.items.length,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class ItemsItem extends StatefulWidget {
  final item;

  ItemsItem({Key key, this.item}) : super(key: key);

  @override
  _ItemsItemState createState() => new _ItemsItemState();
}

class _ItemsItemState extends State<ItemsItem> {
  final GlobalKey<ScaffoldState> _mainState = new GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    bool _isCompleted = widget.item.isCompleted;

    return new ListTile(
      key: _mainState,
      title: new Row(
        children: <Widget>[
          new Expanded(child: new Text(widget.item.name)),
          new Checkbox(
            value: _isCompleted,
            onChanged: (bool newValue) {
              setState(() {
                _isCompleted = newValue;
              });
            },
          ),
        ],
      ),
    );
  }
}

this doesn't seem to change the value

setState(() {
    _isCompleted = newValue;
});

any ideas?

edit: Item class

class Item {
  final int id;
  final String name;
  final bool isCompleted;

  Item({
    this.id,
    this.name,
    this.isCompleted,
  });

  Item.fromJson(Map json)
      : id = json['id'],
        name = json['name'],
        isCompleted = json['isCompleted'],

  set isCompleted(bool value) {
    isCompleted = value;
  }
}

Upvotes: 1

Views: 7214

Answers (1)

Bread Breeder
Bread Breeder

Reputation: 144

_isCompleted is a local variable inside the build method. When the Checkbox's state changes you set the local variable to the new value. setState results in the build method being called again which fetches the old and unchanged value from widget.item.isCompleted. You need to set widget.item.isCompleted to the new changed value:

setState(() {
    widget.item.isCompleted = newValue;
});

Btw since your ItemsItem is just a ListTile containing a row with a Text and a Checkbox you should rather use the built-in widget CheckboxListTile

Upvotes: 5

Related Questions