Not able to delete in onDismissible

937 views Asked by At

I have a code, that uses dismissible in the listview (showes items from database). After dismissing an item it is supposed to show snackbar but it is not showing it and it seems that the dismissible is still part of the tree. Can you help me with that?

return ListView.builder(
  itemCount: count,
  itemBuilder: (BuildContext context, int position) {
    final ThemeData theme = Theme.of(context);

    return Dismissible(

      key: Key(this.objs[position].id.toString()),
      onDismissed: (direction) {
        setState(() async {
          int result = await helper.delete(this.objs[position].id);
        });
        Scaffold.of(context)
            .showSnackBar(SnackBar(
            content: Text(this.objs[position].title + "dismissed")));
      },
      background: Container(
          color: Colors.red,
          child: const ListTile(
              leading: Icon(Icons.delete, color: Colors.white, size: 36.0)
          )
      ),

      child: ListTile(
        leading: CircleAvatar(
          backgroundColor: getColor(this.objs[position].priority),
          child: Text(this.objs[position].id.toString()),
        ),
        title: Text(obj[position].title),
        subtitle: Text(objs[position].date),
        onTap: () {
          debugPrint("Tapped on " + objs[position].id.toString());
          navigateToDetail(this.objs[position]);
        },
      ),
    );
  },
);

this is called inside a Scaffold. And objs is a list that contains all my objects from the database.

Here is my delete code that is called inside onDismissed:

    Future<int> delete(int id) async {
    Database db = await this.db;
    var result = await db.rawDelete("DELETE FROM $tblT WHERE $colId=$id");
    return result;
  }

I've noticed if I delete one item, and immediately try to create another one (I have an option to insert to DB): It sometimes throws the error: A dismissed Dismissible widget is still part of the tree

Update: Moved the delete part, before setState and I am getting the error: A dismissed Dismissible widget is still part of the tree every time I swipe to dismiss

2

There are 2 answers

1
Yash On

Inside content in SnackBar you can try :

Text(this.obj[position].title.toString() + "dismissed")
12
chemamolins On

You could try the following code for the onDismissed: property.

The problem is the future inside the onDismissed function. We need to reorder the async and await keywords.

Anyway, take care with the timings when removing successive items.

onDismissed: (direction) async {
    String title = this.obj[position].title;
    await helper.delete(this.obj[position].id);
    setState(() {});
    Scaffold.of(context)
       .showSnackBar(SnackBar(content: Text("$title dismissed")));
},

It also moves the async out of the setState() and stores the title to be used later by the SnackBar.