Dismissible Widget - Flutter Widget Guide By Flutter Agency

Dismissible Widget – Flutter Widget Guide By Flutter Agency

What is Dismissible Widget in Flutter?

Dismissible Widget is a widget that can be dismissed by dragging in the indicated direction.

In Flutter, when users need to create a widget that can be dismissed, the user can wrap the widget as the child of Dismissible. Dismissible is usually used to wrap each list item so that it can be dismissed, either horizontally or vertically.

We will be showing you examples of how to use the widget, including how to show the confirmation modal, set backgrounds that will be shown when the child is being dismissed and set dismiss directions.

Default Constructor for it will look like the below:

Dismissible(
{required Key key,
required Widget child,
Widget? background,
Widget? secondaryBackground,
ConfirmDismissCallback? confirmDismiss,
VoidCallback? onResize,
DismissUpdateCallback? onUpdate,
DismissDirectionCallback? onDismissed,
DismissDirection direction = DismissDirection.horizontal,
Duration? resizeDuration = const Duration(milliseconds: 300),
Map<DismissDirection, double> dismissThresholds = const <DismissDirection, double>{},
Duration movementDuration = const Duration(milliseconds: 200),
double crossAxisEndOffset = 0.0,
DragStartBehavior dragStartBehavior = DragStartBehavior.start,
HitTestBehavior behavior = HitTestBehavior.opaque}
);

In the Above constructor, all fields marked with @required must not be empty.

Users are required to pass the key and child. key becomes very important since the widget can be removed from the widget list. If there are multiple Dismissible Widget, make sure each has a unique key. Be careful not to use an index as a key as dismissing a widget can change the index of other widgets.

The second required property is a child where you need to pass the widget that can be dismissed.

Another important property is onDismissed(). It’s a callback function accepting one parameter of type DismissDirection. Inside, you can define what to do after the widget has been dismissed. For example, you can remove the widget from the list.

Properties:

  • Key key: The widget key, is used to control if it should be replaced.
  • Widget child: The widget below this widget is in the tree.
  • Widget background: A widget stacked behind the child. If secondaryBackground is set, it’s only shown when the child is being dragged down or to the right.
  • Widget secondaryBackground: A widget stacked behind the child. It’s only shown when the child is being dragged up or to the left.
  • ConfirmDismissCallback confirmDismiss: Gives the app an opportunity to confirm or veto a pending dismissal.
  • VoidCallback onResize: A callback that will be called when the widget changes size.
  • DismissDirectionCallback onDismissed: A callback that will be called when the widget has been dismissed.
  • DismissDirection direction: The direction in which the widget can be dismissed.Defaults to DismissDirection.horizontal.

Supported DismissDirections are:

  1. endToStart(from right to left)
  2. startToEnd (from left to right)
  3. horizontal (both from right to left and left to right)
  4. up
  5. down
  6. vertical (both up and down)
  • Duration resizeDuration: The amount of time the widget will spend contracting before onDismissed is called. Defaults to const Duration(milliseconds: 300).
  • Map<DismissDirection, double> dismissThresholds: The offset threshold the item has to be dragged in order to be considered dismissed. Defaults to const <DismissDirection, double>
  • Duration movementDuration: The duration to dismiss or back to the original position if not dismissed. Defaults to const Duration(milliseconds: 200).
  • double crossAxisEndOffset: The end offset across the main axis after the card is dismissed. Defaults to 0.0.
  • DragStartBehavior dragStartBehavior: How the drag start behaviour is handled. Defaults to DragStartBehavior.start.

How to use Dismissible Widget in Flutter?

The following code snippet tells us how to implement the Dismissible Widget in Flutter.

To Implement Dismissible Widget we first need to create a ListView Widget that shows the data in the list.

We will create a _valuesArray[] like below.

List<String> _valuesArray = [
  'One',
  'Two',
  'Three',
  'Four',
  'Five',
];

Now Define a ListView Widget like the below code snippet.

ListView.separated(
        itemCount: _valuesArray.length,
        padding: const EdgeInsets.all(5.0),
        separatorBuilder: (context, index) => Divider(
              color: Colors.black,
            ),
        itemBuilder: (context, index) {
          return Dismissible(
            key: Key('item ${_valuesArray[index]}'),
            onDismissed: (DismissDirection direction) {
              if (direction == DismissDirection.startToEnd) {
                print("Add to favorite");
              } else {
                print('Remove item');
              }

              setState(() {
                _valuesArray.removeAt(index);
              });
            },
            child: ListTile(
              leading: Icon(
                Icons.account_balance_wallet,
                size: 50,
              ),
              title: Text(_valuesArray[index]),
              subtitle: Text('Description here'),
            ),
          );
        });

We will get output like the below:

Dismissible Widget - Flutter Widget Guide By Flutter Agency

Dismissible Widget

  • Showing Confirmation from the User

Dismissible is often used for delete action. When the User found that performed action is crucial and cannot be undone, it’s better to show confirmation before the action defined inside onDismissed is performed.

confirmDismiss will have a code snippet like below:

confirmDismiss: (DismissDirection direction) async {
               return await showDialog(
                  context: context,
                  builder: (BuildContext context) {
                    return AlertDialog(
                      title: const Text("Delete Confirmation"),
                      content: const Text(
                          "Are you sure you want to delete this item?"),
                      actions: <Widget>[
                        TextButton(
                          onPressed: () => Navigator.of(context).pop(true),
                          child: const Text("Delete"),
                        ),
                        TextButton(
                          onPressed: () => Navigator.of(context).pop(false),
                          child: const Text("Cancel"),
                        ),
                      ],
                    );
                  },
                );
              },

Now when the user tap on the item and the user will get ConfirmationBox like the below:

Dismissible Widget - Flutter Widget Guide By Flutter Agency

Dismissible Widget

  • SettingUp Background Color

Setting up Background Color user needs to set the background & secondaryBackground like below:

background: Container(
              color: Colors.orange,
              child: Padding(
                padding: const EdgeInsets.all(15),
                child: Row(
                  children: [
                    Icon(
                      Icons.favorite,
                      color: Colors.white,
                    ),
                    Text(
                      'Add to favorites',
                      style: TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
            ),
            secondaryBackground: Container(
              color: Colors.red,
              child: Padding(
                padding: const EdgeInsets.all(15),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    Icon(
                      Icons.delete,
                      color: Colors.white,
                    ),
                    Text(
                      'Move to trash',
                      style: TextStyle(color: Colors.white),
                    ),
                  ],
                ),
              ),
            ),

When a user clicks on add to favourite and move to trash  user will get a background colour like below:

Conclusion:

In this article, we have been through What is Dismissible Widget in Flutter along with how to implement it in Flutter.

Thanks for reading !!!

Do let us know your suggestion/feedback for the same.

FlutterAgency is a central point for Flutter developers, attracting thousands daily with its extensive range of materials, including detailed widget guides and practical project examples. It stands as the premier educational center for mastering Flutter.

Nirali Patel

Written by Nirali Patel

Nirali Patel is a dedicated Flutter developer with over two years of experience, specializing in creating seamless mobile applications using Dart. With a passion for crafting user-centric solutions, Nirali combines technical proficiency with innovative thinking to push the boundaries of mobile app development.

Leave a comment

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


ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields

✓ Valid number ✕ Invalid number
our share of the limelight

as seen on