多个小部件使用的ReorderableListViewChildGlobalKey



我理解每个项目都需要一个键来唯一地标识它,特别是因为它们可以移动。我得到的错误是:

key [_ReorderableListViewChildGlobalKey ValueKey#46dc3]被多个小部件使用

列表中的每个项目都已经在我的可解散小部件中唯一标识。

Widget mainCardWidget(BuildContext context) {
return ReorderableListView(
onReorder: onReorder,
physics: const BouncingScrollPhysics(
parent: AlwaysScrollableScrollPhysics()),
children: _getListItems(),
);
}
void onReorder(int oldIndex, int newIndex) {
setState(() {
if (newIndex > oldIndex) {
newIndex -= 1;
}
final Rung element = _items.removeAt(oldIndex);
_items.insert(newIndex, element);
});
}
List<Widget> _getListItems() => _items
.asMap()
.map((i, item) => MapEntry(i, _buildTenableListTile(item, i)))
.values
.toList();
Widget _buildTenableListTile(Rung item, int index) {
return Dismissible(
key: Key(item.rungId),
onDismissed: (direction) {
setState(() {
_items.removeAt(index);
_removeditems.add(item);
});
},
background: Container(color: Colors.red),
child: Padding(
padding: const EdgeInsets.all(20.0),
child: Card(child: cardWithInfoPage(item, context, index)),
),
);
}

我收到了同样的错误,主要原因是我正在填写我的项目。id在initState,所以我把责任移到我的StatefullObject之外,它为我工作。

void main() {
runApp(
MaterialApp(
home: ReorderableListModelView(
items: [
ItemModel(iconReorderable: Icons.menu, replaced: Icons.ac_unit, text: "Teste 1", id: 0),
ItemModel(iconReorderable: Icons.menu, replaced: Icons.ac_unit, text: "Teste 2", id: 1),
ItemModel(iconReorderable: Icons.menu, replaced: Icons.ac_unit, text: "Teste 3", id: 2),
ItemModel(iconReorderable: Icons.menu, replaced: Icons.ac_unit, text: "Teste 4", id: 3),
],
),
),
);
}
class ReorderableListModelView extends StatefulWidget {
final List<ItemModel> items;
const ReorderableListModelView({super.key, required this.items});
@override
State<ReorderableListModelView> createState() => _ReorderableListModelViewState();
}
class _ReorderableListModelViewState extends State<ReorderableListModelView> {
final items = <ItemModel>[];
@override
void initState() {
setState(() {
items.addAll(widget.items);
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: ReorderableListView(
shrinkWrap: true,
onReorder: (oldIndex, newIndex) {
setState(() {
final item = items[oldIndex];
items.removeAt(oldIndex);
items.insert(newIndex, item);
});
},
children: [
for (int i = 0; i < items.length; i++)
ListTile(
key: ValueKey<String>(items[i].id.toString()),
title: Text(items[i].text),
)
],
),
);
}
}

最新更新