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

前端 未结 4 2655
臣服心动
臣服心动 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:11

    import 'package:flutter/material.dart';
    import 'package:vibrate/vibrate.dart';
    
    // Note:
    // Make sure you add the following permissions to your Android Manifest
    // 
    // 
    // In pubspec.yaml file, add following dependency
    // dependencies:
    //   vibrate: ^0.0.4
    
    class TestVibration extends StatefulWidget {
      @override
      _TestVibrationState createState() => _TestVibrationState();
    }
    
    class _TestVibrationState extends State {
    
      bool canVibrate = false;
      @override
      void initState() {
        super.initState();
        _checkIfVibrate();
      }
      _checkIfVibrate() async {
        // check if device can vibrate
        canVibrate = await Vibrate.canVibrate;
      }
    
      @override
      Widget build(BuildContext context) {
        return Container(
          child: RaisedButton(
            child: Text('Vibrate'),
            onPressed: (){
              // FeedbackTypes -> {success, error, warning, selection, impact, heavy, medium, light}
              _getVibration(FeedbackType.warning);
            },
          ),
        );
      }
    
      _getVibration(feedbackType) async {
        if (canVibrate) {
          Vibrate.feedback(feedbackType);
          // Vibrate.vibrate();   // Try this too!
        }
      }
    }
    

提交回复
热议问题