Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 643
David Avatar asked Jan 02 '23 11:01

David


1 Answers

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.

like image 165
Miguel Ruivo Avatar answered Jan 10 '23 20:01

Miguel Ruivo