Flutter复选框类:当我勾选一张卡片时,所有其他人也会被选中

时间:2018-06-11 14:33:35

标签: dart flutter

  bool selected = false;

   new Card(
          shape: selected
              ? new RoundedRectangleBorder(
              side: new BorderSide(color: Colors.blue, width: 2.0),
              borderRadius: BorderRadius.circular(4.0))
              : new RoundedRectangleBorder(
              side: new BorderSide(color: Colors.white, width: 2.0),
              borderRadius: BorderRadius.circular(4.0)),

          child: new Row(


              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[



            new Padding(
              padding: new EdgeInsets.all(8.0),
              child: new Text("${ticketGroups[i]['ticket_name']}",
                  style: const TextStyle(
                      fontSize: 15.0, fontFamily: 'Poppins')),
            ),
            new Padding(
              padding: new EdgeInsets.all(8.0),
              child: new Text(ticketGroups[i]["used"].toString(),
                  style: const TextStyle(
                      fontSize: 15.0, fontFamily: 'Poppins')),
            ),

            new Checkbox(
                value: selected,
                onChanged: (value) {
                  setState(() {
                    selected = !selected;
                  });

                })

When I select one card, the following gets selected too

我希望能够只勾选一张卡片,但是当我勾选任何卡片时,所有卡片都会被勾选。 这些卡也是动态创建的,这会引起问题吗?

2 个答案:

答案 0 :(得分:3)

Günter在评论中说,你需要为每张卡片/列表项目编制一个索引。到目前为止,我见过的最佳选择是使用listBuilder的列表视图,如下所示:

return new ListView.builder(
  itemBuilder: (context, index) => new Card(
      shape: selected[index]
          ? new RoundedRectangleBorder(
          side: new BorderSide(color: Colors.blue, width: 2.0),
          borderRadius: BorderRadius.circular(4.0))
          : new RoundedRectangleBorder(
          side: new BorderSide(color: Colors.white, width: 2.0),
          borderRadius: BorderRadius.circular(4.0)),
          ...
  itemCount: selected.length, // Tell itemBuilder how many items the list has
  ... // Rest of your code...
);

答案 1 :(得分:0)

我认为你需要给每个复选框提供自己的身份。当你动态创建它们时,将它们称为selected1,selected2等。