Tutorial on How to Create a Swipe Action on a List in Flutter

Tutorial on How to Create a Swipe Action on a List in Flutter

Hello everyone, welcome back at porkaone. On this occasion we will learn how to create a swipe action on a list in Flutter or when sliding a row to the left displays an action. Are you curious? Come on, follow the tutorial below.


Swipe Action?

Swipe Action or Swipe Gesture is the user's action of swiping right or left on elements such as cards or lists to activate certain actions. Usually this function is used to delete certain data, mark it as favorite data or other actions.

In our tutorial this time, we will create a simple application. Where this application will display a list of user data. If you slide it to the left, user data will be lost. Please scroll to the bottom of this article to see the final results.


Read Another Article ✨
📰 1. How to Create a Select Dropdown with API in Flutter  read more
📰 2. How to Create a Select Input Dropdown in Flutter  read more
📰 3. How to Make a QR Code Scanner in Flutter ENV read more
📰 4. How to Display Youtube Videos in Flutter  read more



How to Create a Swipe Action with Dismissible in Flutter

1. Create a new flutter project with a free name. Use the latest flutter version or the version that supports null safety. For flutter I use flutter version 2.10 with sdk: ">=2.16.2 <3.0.0"

Flutter Version I Use



2. Open the lib/main.dart file then replace it with the script below.



import 'package:flutter/material.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( title: 'WordPress News', theme: ThemeData( primarySwatch: Colors.blue, ), home: ListUsers(), ); } } class ListUsers extends StatefulWidget { const ListUsers({Key? key}) : super(key: key); @override State<ListUsers> createState() => _ListUsersState(); } class _ListUsersState extends State<ListUsers> { //membuat list data user List<Map<String, dynamic>> userList = [ { 'id': '1', 'name': 'Terry Medhurst', 'email': 'terry@sohu.com', 'image': 'https://robohash.org/hicveldicta.png', }, { 'id': '2', 'name': 'Sheldon Quigley', 'email': 'sheldon@sohu.com', 'image': 'https://robohash.org/doloremquesintcorrupti.png', }, { 'id': '3', 'name': 'Terrill Hills', 'email': 'terrill@sohu.com', 'image': 'https://robohash.org/consequunturautconsequatur.png', }, ]; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Flutter Swipe Action'), ), body: ListView.builder( itemCount: userList.length, itemBuilder: (_, index) { final user = userList[index]; final userId = user['id']; return Dismissible( key: Key(userId), background: Container( color: Colors.red, alignment: Alignment.centerRight, padding: EdgeInsets.symmetric(horizontal: 16.0), child: Icon( Icons.delete, color: Colors.white, ), ), onDismissed: (direction) { setState(() { userList.removeAt(index); }); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('User $userId dismissed')), ); }, child: ListTile( contentPadding: EdgeInsets.only( bottom: 10, ), title: Text(user['name']), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('Email Address: ' + user['email']), ], ), leading: Image.network( user['image'], fit: BoxFit.cover, width: 80, height: 80, ), ), ); }, ), ); } }

Explanation of the script above:
  1. import 'package:flutter/material.dart';: Imports the flutter/material.dart package required to build a Flutter application using Material Design.
  2. void main(): The main function of the Flutter application.
  3. runApp(MyApp());: Starts the application by running the MyApp() widget as the root widget.
  4. class MyApp extends StatelessWidget {: Defines the MyApp class as an instance of StatelessWidget.
  5. @override: Annotation indicating that the next method is an override of a method from the superclass.
  6. Widget build(BuildContext context) {: Build method that describes the appearance of the MyApp widget.
  7. return MaterialApp(...): Returns the MaterialApp widget, which is the root widget of the application with the specified configuration and theme.
  8. title: 'WordPress News',: Application title.
  9. theme: ThemeData(...),: Application theme that uses a blue primarySwatch.
  10. home: ListUsers(),: Set ListUsers as the application's home page.
  11. class ListUsers extends StatefulWidget {: Defines the ListUsers class as an instance of StatefulWidget.
  12. const ListUsers({Key? key}) : super(key: key);: Constructor for the ListUsers class, accepting optional keys.
  13. @override: Annotation indicating that the next method is an override of a method from the superclass.
  14. State<ListUsers> createState() => _ListUsersState();: Overrides the createState method which returns an instance of _ListUsersState, which is the state for the ListUsers widget.
  15. class _ListUsersState extends State<ListUsers> {: Defines the class _ListUsersState as an instance of State that holds the state for the ListUsers widget.
  16. List<Map<String, dynamic>> userList = [...];: Defines a userList list that contains several user data maps.
  17. @override: Annotation indicating that the next method is an override of a method from the superclass.
  18. Widget build(BuildContext context) {: Build method that describes the appearance of the _ListUsersState widget.
  19. return Scaffold(...): Returns the Scaffold widget that provides the basic framework for the application page.
  20. appBar: AppBar(...): Sets the AppBar widget as the app bar at the top of the page.
  21. body: ListView.builder(...): Sets the ListView.builder widget as the page body to display the user's list of items.
  22. final user = userList[index];: Retrieves user data at a specified index from userList.
  23. final userId = user['id'];: Retrieves the 'id' value from the current user data.
  24. return Dismissible(...): Returns a Dismissible widget that implements the swipe action on the user list element.
  25. background: Container(...): Sets the appearance of the background when the element is shifted towards the right.
  26. onDismissed: (direction) {...},: Determines the action performed when an element is shifted and released.
  27. child: ListTile(...): Returns a ListTile widget that displays user information such as name, email, and profile picture.
  28. leading: Image.network(...): Displays the user's profile image as the leading widget in the ListTile.

3. Run the application, if successful then the display will look like the image below.




It's easy isn't it?, you can now create swipe actions in Flutter easily and quickly. You can also improvise by adding other actions. Give actions to api data, combine them with swipe refresh or refresh indicator and so on.

That's it for our short tutorial today on how to create a swipe action on a list in Flutter. Hopefully this short tutorial is useful. If you have any questions, please ask directly in the comments column below. That's all and receive a salary.

Post a Comment

0 Comments