【问题标题】:All children of this widget must have a key in Reorderable Listview此小部件的所有子项都必须在可重排序列表视图中有一个键
【发布时间】:2019-09-05 12:09:13
【问题描述】:

我想重新排序我的列表,但我收到了这个错误。 此小部件的所有子级必须在可重排序列表视图中有一个键

Widget list(list) {
    return Scrollbar(
      child: ReorderableListView(
          header: null,
          onReorder: _onReorder,
          padding: const EdgeInsets.symmetric(vertical: 8.0),
          children: <Widget>[
            ListView.builder(
              itemCount: list.length,
              shrinkWrap: true,
              itemBuilder: (contex, index) {
                return _singleToDoWidget(list[index], index);
              },
            )
          ]),
    );
}

【问题讨论】:

  • 首先,为什么列表视图中有一个列表视图?
  • @RémiRousselet 并不确切知道我以这种方式实现的这个可重新排序的列表视图的想法,我得到了这个关键错误。我浏览了一些示例,但它们使用的是静态列表,在我的应用程序中,我的列表数据来自 api 调用。不知道如何处理这种类型的动态数据。

标签: flutter flutter-layout


【解决方案1】:

key 用于唯一标识列表中的每个项目,因为您将四处移动它们。
你可以这样做:

ReoderableListView(
  header: null,
  onReorder: _onReorder,
  children: [
    for(var i; i < list.length; i++) {
      Container(
        key: ValueKey(list[index]),
        child: _singleToDoWidget(list[index], index),
    }
  ],
);

或者您可以在小部件函数本身中指定key

Widget _singleToDoWidget(String title, int index) {
  return YourRootWidget(
    key: ValueKey(title),
    ...
  ),
}

只是想说明你的实现以及 key 将去哪里

【讨论】:

    【解决方案2】:

    这就是我获得重新排序动态列表的解决方案的方法。

    void _onReorder(int oldIndex, int newIndex) {
         setState(() {
           if (newIndex > oldIndex) {
             newIndex -= 1;
           }
           final dynamic x = list[oldIndex];
           list.removeAt(oldIndex);
           list.insert(newIndex, x);
         });
       }
    
    final List child = map<Widget>(list, (index, i) {
         return _singleToDoWidget(list[index], index);
       });
       return Scrollbar(
         child: ReorderableListView(
             header: null, onReorder: _onReorder, children: child),
       );
    
    Widget _singleToDoWidget(dynamic listItem, index) {
       return ListTile(
         key: ValueKey(index),
         title: Text(listItem.title),
       );
     }
    

    【讨论】:

      猜你喜欢
      • 2011-01-27
      • 1970-01-01
      • 1970-01-01
      • 2011-08-24
      • 2023-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-05
      相关资源
      最近更新 更多