Cara ListView Item bisa digeser kesamping pada Flutter menggunakan Dismissible
Bismillah
Pada ListView, untuk menghapus item biasanya kita lakukan dengan menggesernya ke kiri atau kanan, untuk itu pada Flutter kita bisa gunakan widget bernama Dismissible, caranya mudah sekali seperti berikut ini :
Buat sebuah project baru
Lalu kita bersihkan kodenya menjadi seperti berikut :
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Container();
}
}
Jika sudah, kita buat ListViewnya didalam MyHomePage
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final items = List<String>.generate(20, (i) => "Swipe item ${i + 1}");
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Flutter Dismissible Widget"),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context,i) {
final item = items[i];
return Card(
child: Dismissible(
key: Key(item),
background: Container(
color: Colors.red,
child: Icon(Icons.cancel),
),
secondaryBackground: Container(
color: Colors.blue,
child: Icon(Icons.archive),
),
child: ListTile(
title: Text(item),
),
onDismissed: (DismissDirection direction) {
if (direction == DismissDirection.startToEnd) {
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text("item ${i+1} deleted",), duration: Duration(milliseconds: 300),));
} else {
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text("item ${i+1} archived"), duration: Duration(milliseconds: 300),));
}
setState(() {
items.removeAt(i);
});
},
),
);
}
),
);
}
}