[英]Flutter, Update State for a List of Stateful Widgets inside a Bloc
I am building a grid system and have been trouble updating the State of every widget in a row.我正在构建一个网格系统,并且在连续更新每个小部件的状态时遇到了麻烦。 Their sizes need to dynamically change.它们的大小需要动态变化。 didUpdateWidget() is called in certain cases, but the state of every widget isn't always updated.在某些情况下会调用 didUpdateWidget(),但每个小部件的状态并不总是更新。
Basically how can I loop through a List of StatefulWidgets inside a Bloc function, and have each Widget update their state so the width will change?基本上,我如何遍历 Bloc 函数内的 StatefulWidgets 列表,并让每个 Widget 更新其状态以便宽度发生变化?
All the guides I am finding focus on Stateful Widget updating itself interally, rather than externally.我发现的所有指南都关注有状态小部件在内部而不是外部更新自身。
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),
),
);
}
}
Just to add, this would be the for loop I am using.. I have removed all attempts at writing updateItemWidth from my widget for this question.只是补充一下,这将是我正在使用的 for 循环..我已经删除了从我的小部件中为这个问题编写 updateItemWidth 的所有尝试。
for (int i = 0; i < gridData[row].length; i++) {
gridData[row][i].updateItemWidth(newGridItemsSize);
}
So a solution I found in the end所以我最终找到了一个解决方案
var gridItem = gridData[row][i];
gridData[row].removeAt(i);
gridData[row].insert(i, new ResponsiveGridItemSolid(
gridItem.itemWidth, gridItem.height, gridItem.color, gridItem.content, row, i, gridItem.empty));
Since there is no proper way to force refresh, by removing a Widget completely, and recreating it, you can invoke the build method.由于没有正确的方法来强制刷新,通过完全删除一个 Widget 并重新创建它,您可以调用 build 方法。 I've switched to a StatelessWidget as well.我也切换到 StatelessWidget。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.