Why can't I remove a list item using Dismissible widget ?- Flutter

51 Views Asked by At

Hi I have a problem with Dissmisible widget in Flutter.

I have a list of a model class.

List<TaskModel> tasks = [] ;

I use ListView.seperatd to fill that list with the item below:

buildTaskItem(TaskModel model, context) => Dismissible(
                  key: UniqueKey(),
                  onDismissed: (direction) =>
                      AppCubit.get(context).deleteTask(taskId: model.taskId),
                  child: InkWell(
               // Some code

While the list is like this :

 ListView.separated(
                        physics: const NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemBuilder: (context, index) => buildTaskItem(
                              tasks[index],
                              context,
                            ),
                        separatorBuilder: (context, index) => const SizedBox(
                              height: 8.0,
                            ),
                        itemCount: tasks.length),

As you can notice I am using BloC for state managment and here is the function I'm calling onDismissed:

void deleteTask({required taskId}) {
    FirebaseFirestore.instance
        .collection('users')
        .doc(uId)
        .collection('tasks')
        .doc(taskId)
        .delete()
        .then((value) {

      emit(DeletePostSuccessState());
      getTask();
    }).catchError((error) {
      emit(DeletePostErrorState(error));
    });
  }

I get an error saying : a dismissed dismissible widget is still part of the tree.

When I swipe right to delete certain task my app gets a dark screen. Everytime I have to rebuild.

I know the problem is with the key because I tried to delete using longPress on the widget and it worked.

IMPORTANT : It's right that when I swipe right to delete a task my app crashes as I said but the task itself gets deleted from firestroe . So when I run the app again the deleted task is actually no longer there.

I tried some solutions written here in the website like using UniqueKey() or put model.taskId (documentID) as a key but nothing worked yet.

1

There are 1 best solutions below

0
Hunter On

I solved it. It wasn't about the key but about the state, I was emitting a state for delete which was not necessary in my case, just call getTask and everything went good.