Flutter:在设备上振动非标准时间长度

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

我正在尝试为 Android 构建一个 Flutter 应用程序,它使 phone 和

都振动

我找到了产生触觉反馈的方法,例如HapticFeedback.vibrateHapticFeedback.lightImpact;但是,none 允许我控制振动的长度。

有什么方法可以让 phone 振动指定的时间长度(例如 250 毫秒)?

这是一个可以完成这项工作的插件。 https://pub.dartlang.org/packages/vibrate

包中的示例:

// Check if the device can vibrate
bool canVibrate = await Vibrate.canVibrate;

对于iOS:

// Vibrate
// Vibration duration is a constant 500ms because 
// it cannot be set to a specific duration on iOS.
Vibrate.vibrate()

对于Android

// Vibrate with pauses between each vibration
final Iterable<Duration> pauses = [
    const Duration(milliseconds: 500),
    const Duration(milliseconds: 1000),
    const Duration(milliseconds: 500),
];
// vibrate - sleep 0.5s - vibrate - sleep 1s - vibrate - sleep 0.5s - vibrate
Vibrate.vibrate(pauses);

请注意,只有 android

的自定义振动

我正在回答我自己的问题,因为我找到了一个适用于 Android 的解决方案;使用插件 vibrate,以下代码非常适合发送自定义振动长度和振动模式:

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;
    }
  }
}