Undo a Swipe
Part of the Lists and Screens section of Coddy's Flutter journey. Lesson 27 of 33.
A swipe is easy to do by accident, so good apps offer a way back: a SnackBar that says what was removed, with an Undo button. A SnackBarAction is that button:
SnackBar(
content: Text('$item removed'),
action: SnackBarAction(
label: 'Undo',
onPressed: () {
setState(() {
items.insert(index, item);
});
},
),
)To put the item back where it was, remember its place before you remove it. items.indexOf(item) is its position, items.removeAt(index) removes it, and items.insert(index, item) puts it back at that same position.
items.add(item) would bring it back too, but at the end of the list.
Challenge
MediumWhen an item is swiped away, show a SnackBar saying Milk removed (with the item's name) and an Undo action that puts the item back in the same place.
Try it yourself
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(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final List<String> items = ['Milk', 'Bread', 'Eggs', 'Apples', 'Cheese'];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('${items.length} items')),
body: ListView(
children: [
for (String item in items)
Dismissible(
key: ValueKey(item),
onDismissed: (direction) {
setState(() {
items.remove(item);
});
},
child: ListTile(title: Text(item)),
),
],
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lists and Screens
1Scrolling Lists
A List That ScrollsList TilesLeading and TrailingTap a List TileDividers Between Rows6Tabs, Drawers and Swipes
Tabs With a Navigation BarFilled Icons for the Open TabA Side DrawerSwipe to DeleteUndo a SwipePractice on your own: Online Flutter compiler