Open In App

Flutter – Dismissible Widget

Last Updated : 16 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Dismissible widget in Flutter is used to create items that can be dismissed by swiping them off the screen. It’s commonly used in lists or grids where you want to provide a way for users to remove items with a swipe gesture. In this article, we are going to implement the Dismissible widget and explore some properties of it. A sample video is given below to get an idea about what we are going to do in this article.

Basic Syntax of Dismissible Widget

Dismissible(
key: UniqueKey(), // or any unique key for tracking items
child: YourContentWidget(),
background: YourBackgroundWidget(),
secondaryBackground: YourSecondaryBackgroundWidget(),
confirmDismiss: (DismissDirection direction) async {
// Your confirmation logic goes here
// Return true to allow dismissal, false to prevent it
return true;
},
onDismissed: (DismissDirection direction) {
// Your action when item is dismissed goes here
},
onResize: () {
// Your resize animation logic goes here (optional)
},
direction: DismissDirection.endToStart, // or other DismissDirection values
dragStartBehavior: DragStartBehavior.start, // or DragStartBehavior.down
)

Required Tools

To build this app, you need the following items installed on your machine:

  • Visual Studio Code / Android Studio
  • Android Emulator / iOS Simulator / Physical Device device.
  • Flutter Installed
  • Flutter plugin for VS Code / Android Studio.

Step By Step Implementations

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package

First of all import material.dart file.

import 'package:flutter/material.dart';

Step 3: Execute the main Method

Here the execution of our app starts.

Dart




void main() {
  runApp(MyApp());
}


Step 4: Create MyApp Class

In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.

Dart




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      title: 'Dismissible Example',
      home: DismissibleExample(),
    );
  }
}


Step 5: Create DismissibleExample Class

In this class we are going to Implement the Dismissible widget whenever the user Swipe the List items then the swiped items are deleted.Comments are added for better understanding.

Dismissible(
key: Key(item), // Unique key for each item
onDismissed: (direction) {
// Remove the item from the list when dismissed
setState(() {
items.removeAt(index);
});
// Show a snackbar to indicate item removal
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('$item dismissed'),
),
);
},
background: Container(
color: Colors.red, // Background color when swiping
child: Icon(
Icons.delete,
color: Colors.white,
size: 36,
),
alignment: Alignment.centerRight,
padding: EdgeInsets.only(right: 20),
),
child: ListTile(
title: Text(item),
),
);

Dart




class DismissibleExample extends StatefulWidget {
  @override
  _DismissibleExampleState createState() => _DismissibleExampleState();
}
  
class _DismissibleExampleState extends State<DismissibleExample> {
  // Sample list of items
  List<String> items = List.generate(5, (index) => 'Item ${index + 1}');
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dismissible Example'),
      ),
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) {
          final item = items[index];
          return Dismissible(
            key: Key(item), // Unique key for each item
            onDismissed: (direction) {
              // Remove the item from the list when dismissed
              setState(() {
                items.removeAt(index);
              });
  
              // Show a snackbar to indicate item removal
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text('$item dismissed'),
                ),
              );
            },
            background: Container(
              color: Colors.red, // Background color when swiping
              child: Icon(
                Icons.delete,
                color: Colors.white,
                size: 36,
              ),
              alignment: Alignment.centerRight,
              padding: EdgeInsets.only(right: 20),
            ),
            child: ListTile(
              title: Text(item),
            ),
          );
        },
      ),
    );
  }
}


Here is the full Code of main.dart file

Dart




import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      title: 'Dismissible Example',
      home: DismissibleExample(),
    );
  }
}
  
class DismissibleExample extends StatefulWidget {
  @override
  _DismissibleExampleState createState() => _DismissibleExampleState();
}
  
class _DismissibleExampleState extends State<DismissibleExample> {
  // Sample list of items
  List<String> items = List.generate(5, (index) => 'Item ${index + 1}');
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dismissible Example'),
      ),
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) {
          final item = items[index];
          return Dismissible(
            key: Key(item), // Unique key for each item
            onDismissed: (direction) {
              // Remove the item from the list when dismissed
              setState(() {
                items.removeAt(index);
              });
  
              // Show a snackbar to indicate item removal
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Text('$item dismissed'),
                ),
              );
            },
            background: Container(
              color: Colors.red, // Background color when swiping
              child: Icon(
                Icons.delete,
                color: Colors.white,
                size: 36,
              ),
              alignment: Alignment.centerRight,
              padding: EdgeInsets.only(right: 20),
            ),
            child: ListTile(
              title: Text(item),
            ),
          );
        },
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads