Flutter: Master Vibration Controls with the Vibration Plugin

Published on by Flutter News Hub

Flutter: Master Vibration Controls with the Vibration Plugin

In the world of mobile app development, user experience is paramount. Vibrations have become an integral part of enhancing user engagement and providing tactile feedback. To seamlessly integrate vibrations into your Flutter applications, the vibration plugin offers a comprehensive set of methods.

Getting Started with the Vibration Plugin

  1. Add the vibration dependency to your pubspec.yaml file:
dependencies:
  vibration: ^1.8.4
  1. Import the package in your Dart code:
import 'package:vibration/vibration.dart';

Vibration Methods for Granular Control

1. hasVibrator()

Check if the device supports vibration capabilities:

if (await Vibration.hasVibrator()) {
  Vibration.vibrate();
}

2. hasAmplitudeControl()

Determine if the device can control vibration amplitude (Android 8.0+ only):

if (await Vibration.hasAmplitudeControl()) {
  Vibration.vibrate(amplitude: 128);
}

3. hasCustomVibrationsSupport()

Verify if the device supports custom vibrations (duration, pattern, intensity):

if (await Vibration.hasCustomVibrationsSupport()) {
  Vibration.vibrate(duration: 1000);
} else {
  Vibration.vibrate();
  await Future.delayed(Duration(milliseconds: 500));
  Vibration.vibrate();
}

4. vibrate()

With Specific Duration:

Vibration.vibrate(duration: 1000);  // Vibrate for 1 second

With Specific Duration and Amplitude:

Vibration.vibrate(duration: 1000, amplitude: 128);  // Vibrate for 1 second at amplitude 128

With Vibration Pattern:

Vibration.vibrate(pattern: [500, 1000, 500, 2000]);  // Wait 500ms, vibrate 1s, wait 500ms, vibrate 2s

With Vibration Pattern and Intensities:

Vibration.vibrate(pattern: [500, 1000, 500, 2000], intensities: [1, 255]);  // Vary intensities from 1 (min) to 255 (max)

5. cancel()

Stop any ongoing vibration:

Vibration.cancel();

Supports vibration with duration and pattern.

  • Uses VibrationEffect on Android 8+ for enhanced control.

iOS Specifics

  • Supports vibration with duration and pattern on CoreHaptics devices.
  • Emulates pattern with 500ms long vibrations on older devices.
  • hasCustomVibrationsSupport can be used to check for CoreHaptics support.

Conclusion

The vibration plugin provides a robust API to add tactile feedback to your Flutter applications. With its comprehensive set of methods, you can precisely control the duration, pattern, and intensity of vibrations, enhancing the user experience and adding a touch of refinement. Utilize the code examples provided to seamlessly integrate vibration functionality into your apps and captivate your users.

Flutter News Hub