Flutterexperts

Empowering Vision with FlutterExperts' Expertise
Dismissible In Flutter

In Flutter, assuming you want to make a widget that can be dismissed, you can wrap the widget as the child of Dismissible. A dismissible Widget in Flutter is typically used to wrap each list item with the goal that it tends to be excused, either horizontally or vertically direction.

This blog will explore the Dismissible In Flutter. We perceive how to execute a demo program. We will figure out how to utilize the widget, including how to show the confirmation dialog, set backgrounds that will be shown when the child is being dismissed, and set dismissed directions in your Flutter applications.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

A widget can be dismissed by dragging in the demonstrated direction. Dragging or hurling this widget in the DismissDirection makes the child slide out of view.

Demo Module ::

This demo video shows how to use the dismissible in a flutter and shows how a dismissible will work in your flutter applications. We will show a user dragging or fingering by dismissing a widget. It will be shown on your devices.

Constructor:

To utilize Dismissible, you need to call the constructor underneath:

You are required to pass the key (Key) and child (Widget). key turns out to be vital since the widget can be taken out from the widget list. If there are different dismissible widgets, ensure each has a unique key.

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

Be mindful not to involve the index as a key as dismissing a widget can change the index of different widgets. The second required property is a child where you want to pass the widget that can be dismissed.

Another significant property is onDismissed. It’s a callback function tolerating one boundary of type DismissDirection. Inside, you can characterize what to do after the widget has been dismissed. For instance, you can eliminate the widget from the list.

Properties:

There are some properties of Dismissible are:

  • > key — This property is used to control if it should be replaced.
  • > child — This property is used below this widget in the tree.
  • > background — This property is used to stack behind the child. It secondaryBackground is set, it’s only shown when the child is being dragged down or to the right.
  • secondaryBackground — This property is used to stack behind the child. It’s only shown when the child is being dragged up or to the left.
  • > confirmDismiss— This property is used to allow the app to confirm or veto a pending dismissal.
  • > onResize — This property is used for the callback that will be called when the widget changes size.
  • > onDismissed — This property is used for the callback that will be called when the widget has been dismissed.
  • > direction — This property is used to the direction in which the widget can be dismissed. Defaults to DismissDirection.horizontal.
  • > resizeDuration — This property is used to the amount of time the widget will spend contracting before onDismissed is called. Defaults to const Duration(milliseconds: 300).
  • > dismissThresholds — This property is used to the offset threshold the item has to be dragged to be considered dismissed. Defaults to const <DismissDirection, double>{}.
  • > movementDuration — This property is used to the duration to dismiss or back to the original position if not dismissed. Defaults to const Duration(milliseconds: 200).
  • > crossAxisEndOffset — This property is used to the end offset across the main axis after the card is dismissed. Defaults to 0.0.
  • > dragStartBehavior — This property is used for how the drag start behavior is handled. Defaults to DragStartBehavior.start.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called main.dart inside the lib folder.

We will make a basic ListView where the thing can be dismissed. The ListView is made utilizing the accompanying values.

 List<String> items = [
"Watch",
"Jeans",
"Shirt",
"T-Shirt",
"Cup",
"Shoes",
"Cap",
"Shorts",
"Trouser",
"Lower",
];

Here is the code for building the ListView. The itemBuilder, which is utilized to construct the list of items, returns a Dismissible. Notwithstanding the required arguments (key and child), an onDismissed callback is additionally passed. The model tells you the best way to set various actions for every direction.

ListView.builder(
itemCount: items.length,
padding: const EdgeInsets.symmetric(vertical: 16),
itemBuilder: (BuildContext context, index) {
return Dismissible(
key: Key('item ${items[index]}'),
onDismissed: (DismissDirection direction) {
if (direction == DismissDirection.startToEnd) {
print("Add to favorite");
} else {
print('Remove item');
}

setState(() {
items.removeAt(index);
});
},
child: ListTile(
leading: const Icon(
Icons.card_giftcard_rounded,
color: Colors.black,
),
title: Text(
items[index],
style: TextStyle(
color: Colors.black.withOpacity(.6), fontSize: 18),
),
subtitle: Text(
"This Gift is For you",
style: TextStyle(color: Colors.green.withOpacity(.6)),
),
),
);
}
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

> Showing Confirmation

Dismissible is frequently utilized for deleting an activity. On the off chance that you think the performed activity is critical and can’t be scattered, it’s smarter to show affirmation before the activity is characterized inside onDismissed is performed.

You can do it by passing confirmDismissCallback to the constructor. A callback acknowledges one parameter of type DismissDirection and returns Future<bool>. The below model shows an AlertDialog where the client can confirm to delete the item or cancel the action.

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

> Setting Backgrounds

The default dismiss direction is horizontal. You can swipe to the right or left. Swiping left or right might result in an alternate action, relying upon what you characterize in the onDismissed callback. Flutter additionally permits you to set various widgets that will be shown when the child is being dismissed.

Utilize the background to characterize the widget to be shown when the child is swiped to the right and the secondary background for the widget when the child is swiped to the left. Assuming you just set the background, it will be utilized for the two directions.

background: Container(
color: Colors.blue,
child: Padding(
padding: const EdgeInsets.all(15),
child: Row(
children: const [
Icon(Icons.favorite, color: Colors.red),
SizedBox(
width: 8.0,
),
Text('Move 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: const [
Icon(Icons.delete, color: Colors.white),
SizedBox(
width: 8.0,
),
Text('Move to trash',
style: TextStyle(color: Colors.white)),
],
),
),
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_dismissible_demo/splash_screen.dart';

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

class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.teal,
),
debugShowCheckedModeBanner: false,
home: const Splash(),
);
}
}

class DismissibleDemo extends StatefulWidget {
const DismissibleDemo({Key? key}) : super(key: key);

@override
State<DismissibleDemo> createState() => _DismissibleDemoState();
}

class _DismissibleDemoState extends State<DismissibleDemo> {
List<String> items = [
"Watch",
"Jeans",
"Shirt",
"T-Shirt",
"Cup",
"Shoes",
"Cap",
"Shorts",
"Trouser",
"Lower",
];

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.teal,
centerTitle: true,
automaticallyImplyLeading: false,
title: const Text("Flutter Dismissible Demo"),
),
body: ListView.builder(
itemCount: items.length,
padding: const EdgeInsets.symmetric(vertical: 16),
itemBuilder: (BuildContext context, int index) {
return Dismissible(
background: Container(
color: Colors.blue,
child: Padding(
padding: const EdgeInsets.all(15),
child: Row(
children: const [
Icon(Icons.favorite, color: Colors.red),
SizedBox(
width: 8.0,
),
Text('Move 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: const [
Icon(Icons.delete, color: Colors.white),
SizedBox(
width: 8.0,
),
Text('Move to trash',
style: TextStyle(color: Colors.white)),
],
),
),
),
key: ValueKey<String>(items[index]),
onDismissed: (DismissDirection direction) {
setState(() {
items.removeAt(index);
});
},
confirmDismiss: (DismissDirection direction) async {
if (direction == DismissDirection.startToEnd) {
return await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Add Gift to Cart"),
content: const Text(
"Are you sure you want to add this gift in your cart"),
actions: <Widget>[
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text("Yes")),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text("No"),
),
],
);
},
);
} else {
return await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: const Text("Remove Gift"),
content: const Text(
"Are you sure you want to remove this gift item?"),
actions: <Widget>[
ElevatedButton(
onPressed: () => Navigator.of(context).pop(true),
child: const Text("Yes")),
ElevatedButton(
onPressed: () => Navigator.of(context).pop(false),
child: const Text("No"),
),
],
);
},
);
}
},
child: ListTile(
leading: const Icon(
Icons.card_giftcard_rounded,
color: Colors.black,
),
title: Text(
items[index],
style: TextStyle(
color: Colors.black.withOpacity(.6), fontSize: 18),
),
subtitle: Text(
"This Gift is For you",
style: TextStyle(color: Colors.green.withOpacity(.6)),
),
),
);
},
));
}
}

Conclusion:

In the article, I have explained the Dismissible basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Dismissible User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying the Dismissible in your flutter projectsWe will show you what the Introduction is and what are the construction and properties of the Dismissible and make a demo program for working with Dismissible in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Leave comment

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