今回は外部パッケージ「flutter_slidable」の「Slidable」を使用してListTileなどのWidgetをスワイプして削除などのアクションを表示させる方法を紹介します。
目次
「flutter_slidable」の導入
$ flutter pub add flutter_slidable
$ flutter pub get
pubspec.yamlにパッケージを追加・更新
import 'package:flutter_slidable/flutter_slidable.dart';
dartファイルにコピペ
あわせて読みたい


【Flutter】外部パッケージの導入方法|pub.devドキュメントの見方
今回は「外部パッケージの導入方法」と、導入したパッケージの「ドキュメントの見方」について紹介します。 【外部パッケージのインストール方法】 「pub.dev」から導入...
Slidableの使い方


Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter'),
),
body: Slidable(
endActionPane: ActionPane(
motion: DrawerMotion(),
children: [
SlidableAction(
onPressed: (value) {},
backgroundColor: Colors.blue,
icon: Icons.share,
label: 'シェア',
),
SlidableAction(
onPressed: (value) {},
backgroundColor: Colors.red,
icon: Icons.delete,
label: '削除',
),
],
),
child: ListTile(
tileColor: Colors.yellow[100],
leading: Icon(Icons.face),
title: Text(
'Slidable',
),
),
),
),
);
}
スワイプしたいWidgetをSlidableでラップしたら、startActionPaneプロパティ(左から右)・endActionPaneプロパティ(右から左)でスワイプの方向を指定できます。上記コードではendActionPaneのみ使用していますが、両方同時に使用できます。
endActionPaneプロパティにはActionPaneを使用します。ActionPaneのchildrenプロパティにSlidableActionでアクションを追加し、motionプロパティでアニメーション表示を指定します。スワイプ時のアニメーションはドキュメントから確認できます。
サンプルコード


//ソース
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter'),
),
body: Slidable(
endActionPane: ActionPane(
motion: DrawerMotion(),
children: [
SlidableAction(
onPressed: (value) {
print('シェア');
},
backgroundColor: Colors.blue,
icon: Icons.share,
label: 'シェア',
),
SlidableAction(
onPressed: (value) {
print('削除');
},
backgroundColor: Colors.red,
foregroundColor: Colors.white,
icon: Icons.delete,
label: '削除',
),
],
),
child: ListTile(
tileColor: Colors.yellow[100],
leading: Icon(Icons.face),
title: Text(
'Slidable',
),
),
),
),
);
}
}
以上です。