ToDoリストやメールアプリなどで、リスト項目を横にスワイプして削除やアクションを出すUIを見たことはありませんか?
Flutterでもそれが簡単に実装できるのが flutter_slidable
パッケージです。
1. flutter_slidableとは?
flutter_slidable
は、ListViewなどのリスト項目にスワイプ操作を追加できる便利なパッケージです。
左右どちらにもカスタムアクションボタンを表示でき、アニメーションも滑らかです。
2. インストール
pubspec.yaml
に追加:
dependencies:
flutter_slidable: ^3.0.1
※バージョンは pub.dev で確認してください。
flutter pub get
3. 基本的な使い方
以下は、リストをスワイプして削除ボタンを表示する例です。
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
class MyListPage extends StatelessWidget {
final List<String> items = ['りんご', 'バナナ', 'オレンジ'];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Slidableリスト')),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return Slidable(
key: ValueKey(items[index]),
endActionPane: ActionPane(
motion: ScrollMotion(),
children: [
SlidableAction(
onPressed: (context) {
// アクション例
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('${items[index]} を削除')),
);
},
backgroundColor: Colors.red,
icon: Icons.delete,
label: '削除',
),
],
),
child: ListTile(
title: Text(items[index]),
),
);
},
),
);
}
}
4. 左右にアクションを追加する
両側にアクションを追加することも可能です。
Slidable(
startActionPane: ActionPane(
motion: DrawerMotion(),
children: [
SlidableAction(
onPressed: (_) {},
backgroundColor: Colors.green,
icon: Icons.archive,
label: '保存',
),
],
),
endActionPane: ActionPane(
motion: DrawerMotion(),
children: [
SlidableAction(
onPressed: (_) {},
backgroundColor: Colors.red,
icon: Icons.delete,
label: '削除',
),
],
),
child: ListTile(title: Text('アイテム')),
);
5. よく使うモーション種類
モーション名 | 特徴 |
---|---|
ScrollMotion() | スクロール風に滑らかに動く |
DrawerMotion() | ドロワーのようにアクション出現 |
BehindMotion() | 背面からアクションが出現 |
6. まとめ
特長 | 内容 |
---|---|
スワイプ操作対応 | 左右どちらにも可能 |
アクション追加 | アイコン・色・ラベルなどカスタマイズ可能 |
アニメーション | 複数のモーションが用意されている |
複数リスト対応 | ListView , ListTile などで使用可能 |
おわりに
flutter_slidable
を使えば、直感的でリッチな操作感のリストUIを手軽に実装できます。
スワイプで削除・保存・編集などを行いたいアプリでは、まず検討したいパッケージのひとつです。
参考リンク