颤动,复选框状态不会改变,如何?

时间:2018-04-22 22:11:39

标签: flutter setstate

我有一个ListView构建器,可以创建一些ListTitle,其中包含一个复选框。

当我在复选框setStateonChanged时,该值似乎没有变化。

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;
              });
            },
          ),
        ],
      ),
    );
  }
}

这似乎没有改变价值

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

任何想法?

编辑:项目类

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;
  }
}

1 个答案:

答案 0 :(得分:3)

_isCompleted是构建方法中的局部变量。当复选框的状态更改时,您将局部变量设置为新值。 setState导致再次调用构建方法,该方法从widget.item.isCompleted中获取旧的和未更改的值。您需要将widget.item.isCompleted设置为新更改的值:

npm install --save-dev html-webpack-plugin@3

顺便说一句,因为您的ItemsItem只是一个包含带有文本和复选框的行的ListTile,您应该使用内置窗口小部件CheckboxListTile