Flutter: vibrate on device for non-standard length of time

3,188

I'm answering my own question as I've found a solution that works well for Android; using the plugin vibrate, the following code works perfectly well to send custom lengths of vibration and patterns of vibration:

class GoodVibrations {
  static const MethodChannel _channel = const MethodChannel(
      'github.com/clovisnicolas/flutter_vibrate');

  ///Vibrate for ms milliseconds
  static Future vibrate(ms) =>
      _channel.invokeMethod("vibrate", {"duration": ms});

  ///Take in an Iterable<int> of the form
  ///[l_1, p_1, l_2, p_2, ..., l_n]
  ///then vibrate for l_1 ms,
  ///pause for p_1 ms,
  ///vibrate for l_2 ms,
  ///...
  ///and vibrate for l_n ms.
  static Future vibrateWithPauses(Iterable<int> periods) async {
    bool isVibration = true;
    for (int d in periods) {
      if (isVibration && d > 0) {
        vibrate(d);
      }
      await new Future.delayed(Duration(milliseconds: d));
      isVibration = !isVibration;
    }
  }
}
Share:
3,188
Benedict Randall Shaw
Author by

Benedict Randall Shaw

I have a silver medal from the International Mathematics Olympiad (2018), a gold medal from the International Linguistics Olympiad (2018), and two years left to compete again. I have been a reserve for the British team for the International Informatics Olympiad (2017).

Updated on December 05, 2022

Comments

  • Benedict Randall Shaw
    Benedict Randall Shaw over 1 year

    I am trying to build a Flutter application for Android that vibrates the phone both

    • for sufficiently long and sufficiently forcefully that even when the user's phone is in their pocket, the vibration is noticeable
    • in a specific pattern which the user can identify (like Morse code)

    I have found ways of producing haptic feedback, such as HapticFeedback.vibrate, HapticFeedback.lightImpact; however, none of these allow me to control the length of the vibration.

    Is there any way in which I can make the phone vibrate for a specified length of time (e.g. 250ms)?

  • Benedict Randall Shaw
    Benedict Randall Shaw almost 6 years
    Is there any way to have a vibration for a time other than 500ms?
  • Tree
    Tree almost 6 years
    According to the plugin, on iOS there is not. Try to look online
  • Tree
    Tree almost 6 years
    you can check what new haptic api in ios 10 offers. Then maybe you can combine those vibrations
  • Tree
    Tree almost 6 years
    for android, the solution above should be sufficient. Just pass pauses and thats it
  • Daneel
    Daneel almost 6 years
    You should accept your own answer. Many people only click on questions with accepted answers when looking up a specific problem.