Skip to content
DeveloperMemos

Implementing Swipe to Delete in Flutter with Dismissible

Flutter, Dismissible, ListView1 min read

One of the things that I love about Flutter is how much stuff that you can do with it out of the box. One good example of this is Navigator/navigation(sorry React Native you just don't cut it in that regard) - and another which I'm writing about in this article is the Dismissible widget that lets you implement swipe to delete in your ListView in just a couple of lines of code. It really couldn't be any more simple.

For the purpose of this article I'm assuming that you are using a ListView and that you want to give users an easy and intuitive method to dismiss or delete items. Like I said above this can be accomplished using the Dismissible widget. You just need to wrap your ListTile(or whatever you're actually using) in it like this:

1Dismissible(
2 key: Key(item),
3 onDismissed: (direction) {
4 // Do whatever you want to do once it has been swiped away
5 },
6 child: ListTile(title: Text('...')),
7);

So let's quickly unpack this. Child is whatever you are wrapping Dismissible around, the above case is a very simple example that uses ListTile. onDismissed is the method that is called when the user swipes away the list item, it also gives you a parameter - direction - telling you which direction it was swiped in. Lastly is key, which gives a key to each list item - this is important because the swipe to delete functionality won't work without it. If you can't decide what to do for the key you can always just use something like:

1Key(UniqueKey().toString())

And that's pretty much all there is to it. If you add your removal logic to onDismissed everything should work as expected. It's probably also worth mentioning that Dismissible has another prop called background - using this you can add a widget to show under your list item as the user is sliding it away. For example, you could add a Container that has a red background and a trash can icon inside it. Back in February I wrote another article about center-aligning with the Text widget, if you want to check it out you can find it here.