How to make the phone vibrate on long press with Flutter?

2,295

You can wrap your widget (item) that you want to long press in an GestureDetector for example, resulting in something like this:

class MyVibrateButton extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return Center(
      child: GestureDetector(
        onLongPress: () => HapticFeedback.vibrate(),
        child: Container(
          alignment: Alignment.center,
          decoration: BoxDecoration(border: Border.all(width: 2.0)),
          width: 100.0,
          height: 50.0,
          child: Text(
            'My Item\nPress me',
            textAlign: TextAlign.center,
          ),
        ),
      ),
    );
  }
}

Edit: I just found that you can use the Flutter included services.dart package that contains the HapticFeedback class which allows you to trigger different native haptic feedbacks on both platforms. For this example you can use the vibrate() method. Since you want it to vibrate just a little you may want to also try lightImpact() or mediumImpact() . I’ve edited my previous answer accordingly.

Share:
2,295
David
Author by

David

Updated on December 08, 2022

Comments

  • David
    David over 1 year

    Is there a way to make the phone vibrates when the onLongPress "timer" is reached?

    For example:

    1- There is a list of items

    2- I push and hold one item for a "long press"

    3- When the onLongPress "timer" is reached, I want the phone vibrates just a little.

    Doable?

    Thanks