【问题标题】:Flutter, Update State for a List of Stateful Widgets inside a BlocFlutter,更新 Bloc 内有状态小部件列表的状态
【发布时间】: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);

}

【问题讨论】:

    标签: flutter statefulwidget


    【解决方案1】:

    所以我最终找到了一个解决方案

    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));
    

    由于没有适当的方法来强制刷新,通过完全删除一个 Widget,然后重新创建它,您可以调用 build 方法。我也切换到了 StatelessWidget。

    【讨论】:

      猜你喜欢
      • 2020-03-10
      • 2021-03-19
      • 2018-09-01
      • 2020-10-10
      • 2018-07-28
      • 2021-06-17
      • 1970-01-01
      • 2020-02-27
      • 2020-10-20
      相关资源
      最近更新 更多