跳到主內容

實現滑動關閉

如何實現滑動刪除或刪除。

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

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)),
            );
          },
        ),
      ),
    );
  }
}