跳到主内容

实现滑动关闭

如何实现滑动删除或删除。

“滑动删除”模式在许多移动应用程序中很常见。例如,在编写电子邮件应用程序时,你可能希望允许用户滑动电子邮件消息以将其从列表中删除。

Flutter 通过提供 Dismissible 组件使这项任务变得容易。按照以下步骤了解如何实现滑动删除

  1. 创建一个项目列表。
  2. 将每个项目用 Dismissible 组件包裹。
  3. 提供“残留”指示器。

1. 创建一个项目列表

#

首先,创建一个项目列表。有关如何创建列表的详细说明,请参阅 处理长列表 菜谱。

创建数据源

#

在此示例中,你需要 20 个示例项目来处理。为了简单起见,生成一个字符串列表。

dart
final items = List<String>.generate(20, (i) => 'Item ${i + 1}');

将数据源转换为列表

#

在屏幕上显示列表中的每个项目。用户目前还无法滑动删除这些项目。

dart
ListView.builder(
  itemCount: items.length,
  itemBuilder: (context, index) {
    return ListTile(title: Text(items[index]));
  },
)

2. 将每个项目用 Dismissible 组件包裹

#

在此步骤中,通过使用 Dismissible 组件,让用户能够滑动删除列表中的项目。

在用户滑动删除项目后,从列表中删除该项目并显示一个提示框。在实际应用中,你可能需要执行更复杂的逻辑,例如从 Web 服务或数据库中删除该项目。

更新 itemBuilder() 函数以返回一个 Dismissible 组件

dart
itemBuilder: (context, index) {
  final item = items[index];
  return Dismissible(
    // Each Dismissible must contain a Key. Keys allow Flutter to
    // uniquely identify widgets.
    key: Key(item),
    // Provide a function that tells the app
    // what to do after an item has been swiped away.
    onDismissed: (direction) {
      // Remove the item from the data source.
      setState(() {
        items.removeAt(index);
      });

      // Then show a snackbar.
      ScaffoldMessenger.of(
        context,
      ).showSnackBar(SnackBar(content: Text('$item dismissed')));
    },
    child: ListTile(title: Text(item)),
  );
},

3. 提供“残留”指示器

#

目前,该应用程序允许用户滑动删除列表中的项目,但它没有提供关于他们执行操作时会发生什么情况的视觉指示。为了提供一个提示,在用户滑动删除项目时显示一个“残留”指示器。在这种情况下,指示器是红色的背景。

要添加指示器,请为 Dismissible 提供一个 background 参数。

dart
  ScaffoldMessenger.of(context)
      .showSnackBar(SnackBar(content: Text('$item dismissed')));
},
// Show a red background as the item is swiped away.
background: Container(color: Colors.red),
child: ListTile(
  title: Text(item),
),

互动示例

#
import 'package:flutter/material.dart';

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

// MyApp is a StatefulWidget. This allows updating the state of the
// widget when an item is removed.
class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  MyAppState createState() {
    return MyAppState();
  }
}

class MyAppState extends State<MyApp> {
  final items = List<String>.generate(20, (i) => 'Item ${i + 1}');

  @override
  Widget build(BuildContext context) {
    const title = 'Dismissing Items';

    return MaterialApp(
      title: title,
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
      ),
      home: Scaffold(
        appBar: AppBar(title: const Text(title)),
        body: ListView.builder(
          itemCount: items.length,
          itemBuilder: (context, index) {
            final item = items[index];
            return Dismissible(
              // Each Dismissible must contain a Key. Keys allow Flutter to
              // uniquely identify widgets.
              key: Key(item),
              // Provide a function that tells the app
              // what to do after an item has been swiped away.
              onDismissed: (direction) {
                // Remove the item from the data source.
                setState(() {
                  items.removeAt(index);
                });

                // Then show a snackbar.
                ScaffoldMessenger.of(
                  context,
                ).showSnackBar(SnackBar(content: Text('$item dismissed')));
              },
              // Show a red background as the item is swiped away.
              background: Container(color: Colors.red),
              child: ListTile(title: Text(item)),
            );
          },
        ),
      ),
    );
  }
}