How to Add Swipe to Delete Option in Flutter

Swipe to delete is a desirable option for users especially when you are showing a lot of items as a list. It makes user interface of your mobile app more user friendly. In this blog post, let’s discuss how to add swipe to delete option in a ListView in Flutter.

I already have a blog post on how to implement ListView in Flutter. The Flutter widget which is used to enable swipe to dismiss option is Dismissible. You just need wrap your item with Dismissible widget. It accepts so many properties so that you can customize its look and behaviour.

You can use onDismissed property to define actions after swiping gesture. For betterunderstanding go through the following Flutter example of a ListView with swipe to delete option. Once the row is swiped, a snackbar would appear.

import 'package:flutter/material.dart';


class SwipetoDeleteExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Tutorials',
      home: MainScreen()
    );
  }
}

class MainScreen extends StatefulWidget {
  MainScreen({Key key}) : super(key: key);

  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  var data= ["Hey","What's","Up","Dude","This","is","a","Flutter","example","got","it"];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Swipe to Example'),
      ),
      body:Container(
       child: ListView.builder(
  itemCount: data.length,
  itemBuilder: (BuildContext context, int index) {
    return Dismissible(
      background: Container(color: Colors.red),
      key: Key(data[index]),
      child:Container(
      height: 150,
      color: Colors.white,
      child: Center(child: Text('${data[index]}',style: TextStyle(fontSize: 30),)),
    ),
    onDismissed: (direction) {
      // Show a snackbar. This snackbar could also contain "Undo" actions.
    Scaffold
        .of(context)
        .showSnackBar(SnackBar(content: Text("Item ${data[index]} dismissed")));
    // Remove the item from the data source.
    setState(() {
      data.removeAt(index);
    });

    
  },
    );
    
  }
),
      ),
    );
  }
}

And following is the output of the Flutter example.

I hope this Flutter tutorial will help you. Thank you for reading.

Leave a Comment

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