Menu
CoddyTech

Swipe to Delete

Part of the Lists and Screens section of Coddy's Flutter journey. Lesson 26 of 33.

In a mail or shopping app you clear an item by swiping it off the screen. Wrap the row in a Dismissible:

Dismissible(
  key: ValueKey(item),
  onDismissed: (direction) {
    setState(() {
      items.remove(item);
    });
  },
  child: ListTile(title: Text(item)),
)

The row slides away under your finger. When it is gone, onDismissed runs, and you remove the item from your list in setState. If you do not, the list still has it, and Flutter stops with an error: the row it threw away is still in the list.

The key tells Flutter which row is which, so it must be different for every row: ValueKey(item) uses the item itself.

items is final, and you can still remove from it: final means the variable always holds the same list, not that the list never changes.

challenge icon

Challenge

Easy

The app bar counts the items. Make the shopping list swipeable: wrap each ListTile in a Dismissible with ValueKey(item) as its key, and remove the item from items when it is swiped away.

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)
            ListTile(title: Text(item)),
        ],
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lists and Screens

Practice on your own: Online Flutter compiler