FlutterでスワイプしてListViewのアイテムを操作する方法を紹介します。
こんな動きを簡単に実装できます。
結構はまりそうだなーと憂鬱になりながら調べてみたらチュートリアルを見つけて超簡単でした。
ListTile
をDismissible
というウィジェットでラップするだけで実現できます。
実際のコードはこんな感じになります。(行のWidgetを作る部分)
Widget _buildRow() {
return Dismissible(
key: Key("some id"),
background: Container(color: Colors.red), // start to endの背景
secondaryBackground: Container(color:Colors.yellow), // end to startの背景
onDismissed: (direction) {
print(direction);
if (direction == DismissDirection.endToStart) {
print("end to start"); // (日本語だと)右から左のとき
} else {
print("start to end"); // (日本語だと?)左から右のとき
}
},
child: ListTile(
title: Text("hoge"),
onTap: () {
print("row clicked");
},
),
);
}
backgroundにゴミ箱の画像などを表示することで操作がわかりやすくなりますね。