“滑動關閉”模式在許多移動應用中很常見。例如,在編寫電子郵件應用時,你可能希望允許使用者滑動刪除電子郵件,將其從列表中刪除。

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 小部件,讓使用者能夠將專案滑出列表。

使用者滑動刪除專案後,將其從列表中刪除並顯示一個 Snackbar。在實際應用中,你可能需要執行更復雜的邏輯,例如從 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)),
            );
          },
        ),
      ),
    );
  }
}