ReorderableListView throws error when using an extracted widget for itemBuilder?

592 Views Asked by At

If I use an extracted widget in my ReorderableListView Builder it shows this error Every item of ReorderableListView must have a key. but when I use it as a method inside the builder, it works fine.

ReorderableListView.builder(
      itemCount: userList.length,
      itemBuilder: (context, index) {
        final user = userList[index];

        return WidgetList(user: user);        //Not Working, throws the error
      }, 
      onReorder: (int oldIndex, int newIndex) {
            setState(() {
              final index = newIndex > oldIndex ? newIndex - 1 : newIndex;
              final User user = userList.removeAt(index);
              userList.insert(index, user);
            });},
        );

//if I use this, it works fine
Widget MethodList(User user) => ListTile(  
    key: ValueKey(user),
    title: Text(user.firstName),
  );

WidgetList - If I use this, it doesn't work.

class WidgetList extends StatelessWidget {
  final User user;
  const WidgetList({Key? key, required this.user}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return ListTile(
      key: ValueKey(user),
      title: Text(user.firstName),
    );
  }
}

EDIT: WidgetList(user) -> WidgetList(user: user)

1

There are 1 best solutions below

2
On

In WidgetList, you used the name parameter but you passed without the parameter that's why you got the error.

//here key is optional 
return WidgetList(key: ValueKey(user), user: user)
//or
return WidgetList(user: user)

Or, Bind with the container and pass the value key.

return Container(
  key: ValueKey(user),
  child: WidgetList(user: user),
);