How to use Dismissible widget in Flutter
The Dismissible widget in Flutter allows us to create swipeable items that can be dismissed from a list or grid with various actions, such as deleting, archiving, or marking as read. It's a great way to implement common interactions like deleting items with a swipe gesture. Let's dive into the details of using the Dismissible widget:
Constructor and parameters
The Dismissible widget provides a constructor with various parameters to customize its behavior and layout.
const 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
})
Let's take a closer look at each parameter and its purpose.
key: A unique identifier for the widget.child: The main content of the dismissible item.background: Widget displayed when swiping in the primary direction.secondaryBackground: Widget displayed when swiping in the secondary direction.confirmDismiss: Callback to confirm or cancel the dismissal.onResize: Callback when the widget is resizing during dismissal.onUpdate: Callback when the dismissal is updated.onDismissed: Callback when the item is dismissed.direction: Allowed dismissal directions (default: horizontal).resizeDuration: Duration for resizing during dismissal.dismissThresholds: Thresholds for triggering dismissal.movementDuration: Duration for movement during dismissal.crossAxisEndOffset: Offset for end of cross-axis during movement.dragStartBehavior: Behavior for starting dragging.behavior: Behavior for hit testing.
Import required packages
To use the Dismissible widget, we need to import the necessary packages in our Dart file.
import 'package:flutter/material.dart';
Create a list of Dismissible items
We'll need a list of items that we want to make dismissible. For example, let's create a list of strings:
List<String> items = ['Item 1','Item 2','Item 3',// ...add more items];
Implement the Dismissible widget
Now, let's use the Dismissible widget to create swipeable items. Wrap each item in a Dismissible widget within a ListView.builder or any other appropriate widget.
ListView.builder(itemCount: items.length,itemBuilder: (BuildContext context, int index) {return Dismissible(key: Key(items[index]), // Unique key for each itemonDismissed: (direction) {// Handle dismissal actions heresetState(() {items.removeAt(index);});},background: Container(color: Colors.red, // Background color when swipingchild: Icon(Icons.delete, color: Colors.white),alignment: Alignment.centerRight,padding: EdgeInsets.only(right: 20.0),),child: ListTile(title: Text(items[index]),),);},)
Explanation
Line 1–23: Creates a scrollable list using
ListView.builder, which lazily builds its items as they come into view.Line 2: Specifies the number of items in the list based on the length of the
itemslist.Lines 3–22: Defines a callback function (
itemBuilder) to build each item in the list.Line 4: Creates a
Dismissiblewidget for each item.Line 5: Assign a unique key to the
Dismissiblewidget based on the content of theitemslist the givenindex.Lines 6–11: Sets up a callback function (
onDismissed) to handle item dismissal.Line 8–10: Inside the
onDismissedcallback updates the widget's state by removing the dismissed item from theitemslist.
Line 12: Defines the background widget
Containerfor the swipe action.Line 13: Sets the background color to
red.Line 14–16: Displays a delete icon in the red background, aligned to the center-right and with right padding.
Lines 18–20: Defines the main content of the
Dismissiblewidget as aListTile.Line 20: Sets the title of the
ListTileto the content of theitemslist at the givenindex.
Handle dismissal actions
In the onDismissed callback of the Dismissible widget, we can define actions to be performed when an item is dismissed. In this example, the item is removed from the list. We can customize this logic to match our requirements, such as deleting the item from a database or performing other relevant actions.
Customize swipe background
The background parameter of the Dismissible widget allows us to customize the background that appears when the item is swiped. We can use this to display icons, colors, or any other widgets that indicate the action being taken (e.g., deleting).
Code example
We get the following output by putting together the code explained above.
import 'package:flutter/material.dart';
/// Flutter code sample for [Dismissible].
void main() => runApp( DismissibleExampleApp());
class DismissibleExampleApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Dismissible Sample')),
body: DismissibleExample(),
),
);
}
}
class DismissibleExample extends StatefulWidget {
@override
State<DismissibleExample> createState() => _DismissibleExampleState();
}
class _DismissibleExampleState extends State<DismissibleExample> {
List<String> items = [
'Item 1',
'Item 2',
'Item 3',
// ...add more items
];
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
padding: const EdgeInsets.symmetric(vertical: 16),
itemBuilder: (BuildContext context, int index) {
return Dismissible(
background: Container(
color: Colors.green,
),
key: ValueKey<int>(items[index].hashCode),
onDismissed: (DismissDirection direction) {
setState(() {
items.removeAt(index);
});
},
child: ListTile(
title: Text(items[index]),
),
);
},
);
}
}
Conclusion
The Dismissible widget is a valuable asset in Flutter, enabling smooth integration of swipe-to-dismiss behavior within lists and grids. Its customizable features, including swipe directions and background elements, empower developers to create seamless and user-friendly interactions. Overall, the Dismissible widget enhances the usability and interactivity of mobile apps effectively.
Free Resources