Implementing swipe to delete in Flutter

If you have been following along with our stock watcher application, we finished up our last post implementing the pull to refresh feature.  In this post we will continue to enhance the application by implementing swipe to delete.  Swipe to delete allows the user to swipe left on an item in a list (in this case a stock) in order to reveal an action or set of relevant actions.

In order to achieve swipe to delete, we need to wrap each item in the list within a dismissible object.  Open up the stock_list.dart file and locate the _buildStockList method.  We will need to update the itemBuilder as follows:

itemBuilder: (context, index) {
  var s = stocks[index];
  return Dismissible(
    key: Key(s.symbol),
    background: Container(color: Colors.grey),
    onDismissed: (direction) {
      deleteFromList(s);
    },
    child: ListTile(
        title: Text('${s.symbol}'), 
        subtitle: Text(
        '${s.price ?? "price not found"}' + ", last updated: ${s.lastUpdated}"
      )
  ),
  );
}

Our changes so far are quite simple: we have wrapped the ListTile we were creating in a Dismissible widget and provided a few important property settings to the Dismissible constructor –

    • a key to be used to identify items in the list
    • a background color to show when the item is being removed
    • some code (the deleteFromList method) to execute when an item is removed (aka dismissed).

We will implement the deleteFromList method next.  Somewhere above the _buildStockList method, add the following code:

deleteFromList(Stock s) {
    print('removing ${s.symbol}');
    setState(() {
          this.widget.stocks.remove(s);
        });
        Scaffold.of(context).removeCurrentSnackBar(); //in case we are doing more than 1 per 2 seconds...
    Scaffold.of(context).showSnackBar(
      SnackBar(
        content: Text("${s.symbol} removed!"),
        duration: new Duration(seconds: 2),        
        ));
  }

The above code does two things – removes the stock from the list and shows a SnackBar indication at the bottom of the screen.  There are a few small things worth noting though:

  • We have to wrap the removal of the stock within setState to ensure the screen is updated
  • In case the user is quickly swiping to delete multiple items in succession, then we remove any SnackBars on the screen first.

Summary

Some things are just so well designed that implementing them is almost too easy – that is the case with how simplistic it is to add the swipe to delete feature in Flutter.  All we did here was wrap the ListTile in a dismissible object and teach the application how to handle the swipe/delete. As always, the code for this app is available on github here.

I hope you enjoyed this post!

Leave a Reply

Your email address will not be published. Required fields are marked *