How to implement vibration with Flutter for both Android and iOS?

前端 未结 4 2736
臣服心动
臣服心动 2021-02-20 17:29

Using Flutter I am trying to implement vibration on a button click.

I find it surprisingly difficult to be honest. I\'ve tried using the following packages unsuccessfully

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-02-20 18:15

    First, you need to add vibrate: as a dependency to your pubspec.yaml file.

    dependencies:
      flutter:
        sdk: flutter
      vibrate:
    

    After this, you need to import the package in the class that you are using.

    // Import package
    import 'package:vibrate/vibrate.dart';
    

    Now you can this for vibration:

    // Check if the device can vibrate
    bool canVibrate = await Vibrate.canVibrate;
    
    // Vibrate
    // Vibration duration is a constant 500ms because
    // it cannot be set to a specific duration on iOS.
    Vibrate.vibrate();
    
    // Vibrate with pauses between each vibration
    final Iterable 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.vibrateWithPauses(pauses);
    

    or for haptic feedback:

    // Choose from any of these available methods
    enum FeedbackType {
      success,
      error,
      warning,
      selection,
      impact,
      heavy,
      medium,
      light
    }
    
    var _type = FeedbackType.impact;
    Vibrate.feedback(_type);
    

    Source: https://github.com/clovisnicolas/flutter_vibrate

提交回复
热议问题