我想为我的GridView
启用多选功能,但是当我点击任何磁贴时,我自动选择所有磁贴,我想启用选中的磁贴并在磁贴上单击取消选择。请帮助选择和取消选择多个标签。
这是代码:
void toggleSelection() {
setState(() {
if (_isSelected) {
// mycolor=Colors.white;
_textColor = Colors.deepOrange[400];
_borderColor = Colors.deepOrange[300].withOpacity(0.8);
_isSelected = false;
} else {
// mycolor=Colors.grey[300];
_textColor = Colors.black;
_borderColor = Colors.white;
_isSelected = true;
}
});
}
List<Widget> _getTiles() {
final List<Widget> tiles = <Widget>[];
for (int i = 0; i < listResponseData.length; i++) {
bool isSelected = _serviceindex == i;
tiles.add(Container(
//decoration: BoxDecoration(borderRadius: BorderRadius.circular(6), color: Colors.grey),
child: ListTile(
selected: _isSelected,
title: new GestureDetector(
child: new Card(
elevation: 5.0,
child: new Container(
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
border: Border.all(color: _borderColor),
color: Colors.white,
),
child: new Text(listResponseData[i].nativeText,
style: TextStyle(fontSize: 20, color: _textColor),
),
),
),
onTap: () {
toggleSelection();
},
),
),
));
}
return tiles;
}
我已经解决了这个问题,这是工作代码。
List<ResultResponse> newListResponse = new List();
class ResultResponse {
int id;
String name;
String nativeText;
String image;
bool isSelected;
ResultResponse(this.id, this.name, this.nativeText,
this.image, this.isSelected);
}
List<Widget> _getTiles() {
final List<Widget> tiles = <Widget>[];
for (int i = 0; i < newListResponse.length; i++) {
//_isSelected = _serviceindex == i;
tiles.add(Container(
//decoration: BoxDecoration(borderRadius: BorderRadius.circular(6), color: Colors.grey),
child: ListTile(
title: new GestureDetector(
child: new Card(
elevation: 5.0,
child: new Container(
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(6),
border: Border.all(color: newListResponse[i].isSelected ?
Colors.deepOrange[300].withOpacity(0.8) : Colors.white),
color: Colors.white,
),
child: new Text(newListResponse[i].nativeText,
style: TextStyle(fontSize: 20,
color: newListResponse[i].isSelected
? Colors.deepOrange[400] : Colors.black ),
),
),
),
onTap: () {
toggleSelection( i);
},
),
),
));
}
return tiles;
}
void toggleSelection( int i) {
for(int j=0;j<newListResponse.length; j++)
print(newListResponse[j].isSelected);
setState(() {
if (newListResponse[i].isSelected) {
listSelectedServices.remove(i);
newListResponse[i].isSelected = false;
} else {
listSelectedServices.add(i);
newListResponse[i].isSelected = true;
}
});
}