Dismissible Widget – Flutter Widget Guide By Flutter Agency

· 8 min read
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 confirmation modal, set backgrounds that will be shown when the child is being dismissed and set dismiss direction.

Default Constructor for it will look like below:

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

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 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, used to control if it should be replaced.
  • Widget child: The widget below this widget 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 behavior is handled. Defaults to DragStartBehavior.start.

How to use Dismissible Widget in Flutter?

The following code snippet tells us how to implement 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 a 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 below:

Dismissible Widget - Flutter Widget Guide By Flutter Agency

Dismissible Widget

  • Showing Confirmation from 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>[
                      FlatButton(
                        onPressed: () => Navigator.of(context).pop(true),
                        child: const Text("Delete"),
                      ),
                      FlatButton(
                        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 below:

Dismissible Widget - Flutter Widget Guide By Flutter Agency

Dismissible Widget

  • SettingUp Background Color

Setting up Background Color user need to set 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 favorite and move to trash  user will get background color like below:

Conclusion:

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

Thanks for reading !!!

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

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget Guide, Flutter Projects, Code libs and etc.

FlutterAgency.com is one of the most popular online portal dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge on Flutter.

Leave a Reply