我有一个在列表视图中包含一些小部件的小部件。选择一个容器后,它会变成红色,而其他所有容器都将失去其红色外观。
我可以在子状态状态小部件中设置isSelected变量,但无法调用setState或刷新子状态小部件。
class parentWidget extends StatelessWidget {
cells = [
Cell(isSelected: false),
...
Cell(isSelected: false)
]
void _func(int index) {
setState(() {
for (int i = 0; i < cells.length; i++) {
if (i == index) {
cells[i].isSelected = true;
} else {
cells[i].isSelected = false;
}
}
});
}
Widget build(BuildContext context) {
return new ListView(
children: <Widget>[
GestureDetector(
child: cells[0],
onTap: () {
_func(0);
},
),
...
GestureDetector(
child: cells[9],
onTap: () {
_func(9);
},
),
]
)
}
单元文件:
class Cell extends StatefulWidget {
bool isSelected;
@override
Cell createState(this.isSelected) => CellState();
}
class CellState extends State<Cell> {
Widget build(BuildContext context) {
return Container(
color: isSelected ? Colors.red : Colors.black,
);
}