Flutter Slidable Close Programmatically
To close a Flutter Slidable programmatically, you can make use of the `SlidableController`. The `SlidableController` provides methods to open and close slidable widgets manually.
First, add the `flutter_slidable` package to your `pubspec.yaml` file and run `flutter pub get` to import the package.
dependencies:
flutter_slidable: ^x.x.x
Then, in your Flutter widget where you have implemented the `Slidable` widget, create a `SlidableController` instance and set it as a parameter in the `Slidable` widget.
import 'package:flutter_slidable/flutter_slidable.dart';
class MyWidget extends StatefulWidget {
@override
_MyWidgetState createState() => _MyWidgetState();
}
class _MyWidgetState extends State {
// Create the SlidableController instance
SlidableController slidableController = SlidableController();
@override
Widget build(BuildContext context) {
return Slidable(
controller: slidableController, // Set the SlidableController instance
actionPane: SlidableDrawerActionPane(),
actions: [
IconSlideAction(
caption: 'Delete',
color: Colors.red,
icon: Icons.delete,
onTap: () {
// Handle delete action here
},
),
],
child: ListTile(
title: Text('Your list item'),
),
);
}
}
Now, you can use the `close` method of the `SlidableController` instance to close the slidable programmatically from anywhere in your code.
slidableController.close();
This will close the slidable, animating it back to its initial position as if the user had swiped it closed.
You can trigger the `close` method inside your `onTap` function of an action button or any other event where you want to close the slidable programmatically.
Here’s an example where tapping a button outside the `Slidable` widget will close it:
RaisedButton(
onPressed: () {
slidableController.close();
},
child: Text('Close Slidable'),
),