Flutter: How to use HapticFeedback

2020-07-23 08:34发布

问题:

I have imported

import 'package:flutter/services.dart';

and then called

HapticFeedback.lightImpact();

nothing happens. What do I need to do to get it working. I am testing with the latest Flutter version 1.6.6 on a Galaxy S8 running Android 9.0

回答1:

I have the same problem. The below code works fine on iOS but not on Android for HapticFeedback.vibrate();

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

void main() => runApp(MyVibrate());

class MyVibrate extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Vibrate'),
          backgroundColor: Colors.blue,
        ),
        body: SafeArea(
          child: Center(
            child: FlatButton(
                onPressed: () {
                  HapticFeedback.vibrate();
                },
                child: Text('Go Vibrate')),
          ),
        ),
      ),
    );
  }
}

Also, tried: Feedback.forTap(context); but it does not work.

I am looking for a way to get vibrations working on Android without using plugins like https://pub.dev/packages/vibrate that bring challenges for iOS build process at the moment.



回答2:

Please make sure that Vibration feedback is enabled on the android device, and make sure to add

 <uses-permission android:name="android.permission.VIBRATE" />

to the AndroidManifest.xml. See more info here: https://github.com/flutter/flutter/issues/33750



回答3:

Try using this for Android:

Feedback.forTap(context);

More info: https://api.flutter.dev/flutter/material/Feedback-class.html



回答4:

Reading the function description it says:

"On Android, this uses HapticFeedbackConstants.KEYBOARD_TAP."

If the vibrations for the keyboard or 'haptic feedback for tap' are turned off (in the phone's settings), calling HapticFeedback.mediumImpact(); will not have an effect.

To fix the problem one would have to turn on Touch vibration in the phone's settings.



回答5:

import 'package:flutter/services.dart';

  1. import the services package

then inside onTap method

onTap: () { Clipboard.setData(ClipboardData(text: data)); HapticFeedback.heavyImpact(); }

it worked for me.



标签: flutter dart