import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
home: SwipeDismissScreen(),
);
}
}
class SwipeDismissScreen extends StatefulWidget {
const SwipeDismissScreen({super.key});
@override
State<SwipeDismissScreen> createState() => _SwipeDismissScreenState();
}
class _SwipeDismissScreenState extends State<SwipeDismissScreen> {
final List<String> items = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Swipe to Dismiss List'),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return Dismissible(
key: Key(item),
background: Container(
color: Colors.green,
alignment: Alignment.centerLeft,
padding: const EdgeInsets.only(left: 20),
child: const Icon(Icons.check, color: Colors.white),
),
secondaryBackground: Container(
color: Colors.red,
alignment: Alignment.centerRight,
padding: const EdgeInsets.only(right: 20),
child: const Icon(Icons.delete, color: Colors.white),
),
onDismissed: (direction) {
setState(() {
items.removeAt(index);
});
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('$item dismissed')),
);
},
child: ListTile(
title: Text(item),
),
);
},
),
);
}
}
We wrapped each list item in a Dismissible widget with a unique Key based on the item text. This lets Flutter track each item for swipe actions.
We added two background containers: one for swiping right (green with a check icon) and one for swiping left (red with a delete icon). These backgrounds appear as the user swipes.
In the onDismissed callback, we remove the item from the list and call setState to update the UI. We also show a small message confirming the dismissal.
This creates a smooth swipe-to-dismiss experience where users can remove items by swiping left or right.