Open In App

Flutter – Detecting Long Press Effect

Detecting long press effects in Flutter involves the use of the GestureDetector or InkWell widget to detect the Long Press. it’s common to implement long-press detection to provide users with additional functionalities or visual feedback. The long-press event is triggered when a user holds down a particular item for some seconds. To implement this, we can take the help of the onLongPress callback, in InkWell Widget. we can add some visual effects, such as a ripple effect or highlighting, to enhance the user experience. In this article, we are going to detect the long press effect in a ListView Item and show which item is long-pressed by Displaying a SnackBar. A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.



Step 2: Import the Package

First of all import material.dart file.

import 'package:flutter/material.dart';

Step 3: Execute the main Method

Here the execution of our app starts.






void main() {
  runApp(MyApp());
}

Step 4: Create MyApp Class

In this class we are going to implement the MaterialApp and the Scaffold , here we are also set the Theme of our App.




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

Step 5: Create HomePage Class

In this class we are going to a List of String containing Ten items, and we are going to call an userdefine class named as LongPressListItem,Inside the ListView.builder, each item is represented by a LongPressListItem widget.LongPressListItem is a custom widget that takes two parameters:

The LongPressListItem widget itself is an InkWell wrapped around a ListTile. The InkWell provides a visual splash effect when the list item is tapped .Comments are added for better understandings.




class MyHomePage extends StatelessWidget {
  // List of items to be displayed in the ListView
  final List<String> items = List.generate(10, (index) => 'Item $index');
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Detect Long Press'),
      ),
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) {
          return LongPressListItem(
            item: items[index],
            onLongPress: () {
              // Callback when a long press is detected on a list item
              // Show a Snackbar with the information about the long-pressed item
              final snackBar = SnackBar(
                content: Text('Long press on ${items[index]}'),
              );
              ScaffoldMessenger.of(context).showSnackBar(snackBar);
            },
          );
        },
      ),
    );
  }
}

Step 6: Create LongPressListItem Class

The LongPressListItem class in Flutter defines a custom list item widget designed to respond to long-press interactions. Comments are added for better understandings.




class LongPressListItem extends StatelessWidget {
  final String item;
  final VoidCallback onLongPress;
  
  LongPressListItem({required this.item, required this.onLongPress});
  
  @override
  Widget build(BuildContext context) {
    return InkWell(
      onLongPress: onLongPress, // Execute the onLongPress callback
      child: ListTile(
        title: Text(item),
      ),
    );
  }
}

Here is the full Code of main.dart file




import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatelessWidget {
  // List of items to be displayed in the ListView
  final List<String> items = List.generate(10, (index) => 'Item $index');
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Detect Long Press'),
      ),
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, index) {
          return LongPressListItem(
            item: items[index],
            onLongPress: () {
              // Callback when a long press is detected on a list item
              // Show a Snackbar with the information about the long-pressed item
              final snackBar = SnackBar(
                content: Text('Long press on ${items[index]}'),
              );
              ScaffoldMessenger.of(context).showSnackBar(snackBar);
            },
          );
        },
      ),
    );
  }
}
  
class LongPressListItem extends StatelessWidget {
  final String item;
  final VoidCallback onLongPress;
  
  LongPressListItem({required this.item, required this.onLongPress});
  
  @override
  Widget build(BuildContext context) {
    return InkWell(
      onLongPress: onLongPress, // Execute the onLongPress callback
      child: ListTile(
        title: Text(item),
      ),
    );
  }
}

Output:


Article Tags :