【问题标题】:Flutter ListView: widgets doesn't updateFlutter ListView:小部件不更新
【发布时间】:2021-08-06 13:15:36
【问题描述】:

我有一个在 StatefulWidget 内显示一些项目的列表视图:

  ListView.separated(
      shrinkWrap: true,
      itemBuilder: (context, index) {
          return RowItem(
              item: rowsList[index],
              index: index,
          );
      },
      separatorBuilder: (context, index) {
          return Divider(
              height: 20,
              color: Colors.transparent,
          );
      },
      itemCount: rowsList.length,
  ),

RowItem 也是一个 StatefulWidget。

当我从 rowsList 添加和删除项目时,一切正常,但当我尝试更新现有 RowItem 时遇到问题。这是我的更新功能:

  void updateRow(int rowIndex, MyItem item) {
    setState(() {
       rowsList[rowIndex] = item;
    });
  }

但我仍然在 listview 中看到更新项目的旧值。 (MyItem 是一个扩展 Equatable 的对象)。

怎么了?

【问题讨论】:

  • 尝试使用keys。
  • 谢谢,我只是想念将键设置为 RowItem -.-
  • 它能解决您的问题吗?如果是这样,我将我的评论作为实际答案重新发布。
  • 当然,转发答案,我会接受的。

标签: flutter flutter-listview statefulwidget flutter-state


【解决方案1】:

转发我的评论。您应该在每个 RowItem 上使用 Key。

来自 Emily Fortuna here 的更多信息。

【讨论】:

    【解决方案2】:

    试试RowItem小部件试试这个

    变量项;

     @override
       void initState() {
        item = widget.item;
          super.initState();
        }
    @override
      void didUpdateWidget(covariant SleepDeckStepper oldWidget) {
        item = widget.item;
        super.didUpdateWidget(oldWidget);
      }
    

    问题是item 参数没有为RowItem 更新

    【讨论】:

      猜你喜欢
      • 2018-11-01
      • 2020-08-18
      • 1970-01-01
      • 2020-08-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 2020-10-20
      • 2021-01-10
      相关资源
      最近更新 更多