【发布时间】:2020-11-14 00:50:15
【问题描述】:
我正在构建一个网格系统,并且在连续更新每个小部件的状态时遇到了麻烦。它们的大小需要动态变化。在某些情况下会调用 didUpdateWidget(),但并不总是更新每个小部件的状态。
基本上,我如何在 Bloc 函数中循环遍历 StatefulWidgets 列表,并让每个 Widget 更新它们的状态以便宽度会改变?
我发现的所有指南都集中在 Stateful Widget 内部更新自身,而不是外部更新。
class ResponsiveGridItem extends StatefulWidget {
double itemWidth;
double height;
Color color;
String content;
int row;
int column;
bool empty;
ResponsiveGridItem(
this.itemWidth ,
this.height ,
this.color,
this.content,
this.row,
this.column,
this.empty,);
@override
ResponsiveGridItemState createState() => ResponsiveGridItemState();
}
class ResponsiveGridItemState extends State<ResponsiveGridItem> {
double itemWidth = 37;
double height = 100;
Color color = Colors.blue;
String content = "";
int row;
int column;
bool empty = true;
@override
initState() {
super.initState();
itemWidth = widget.itemWidth;
// print("init itemWdith is " + itemWidth.toString());
height = widget.height;
color = widget.color;
content = widget.content;
row = widget.row;
column = widget.column;
empty = widget.empty;
}
@override
void didUpdateWidget(ResponsiveGridItem oldWidget) {
itemWidth = widget.itemWidth;
color = widget.color;
row = widget.row;
column = widget.column;
content = widget.content;
empty = widget.empty;
super.didUpdateWidget(oldWidget);
}
@override
Widget build(BuildContext context) {
return Container(
height: 100,
width: itemWidth,
alignment: Alignment(0, 0),
color: color,
child: DragTargetWidget(
row,
column,
empty,
cardItem: CardItem(content: content, width: itemWidth),
),
);
}
}
补充一下,这将是我正在使用的 for 循环。我已经删除了从我的小部件中为这个问题编写 updateItemWidth 的所有尝试。
for (int i = 0; i < gridData[row].length; i++) {
gridData[row][i].updateItemWidth(newGridItemsSize);
}
【问题讨论】: