In this example, we are going to show you the easiest way to implement vibration programmatically with Dart in Flutter App. You can control duration and pattern of vibration.
First, you need to add vibration Flutter package in your project depedency by adding following lines in pubspec.yaml file.
dependencies:
flutter:
sdk: flutter
vibration: ^1.7.3
Import Package to Script:
import 'package:vibration/vibration.dart';
Add Vibration permission in android/app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.VIBRATE" />
if (await Vibration.hasVibrator()) { //check if device has vibration feature
Vibration.vibrate(); //500 millisecond vibration
}
Vibration.vibrate(duration: 1000); //1 Sec = 1000 millisecond
Vibration.vibrate(
pattern: [
500, //wait 0.5 second
1000, //vibrate 1 second
500, //wait 0.5 second
3000 //vibrate 3 second.
//add mroe pattern here
]
); //1 Sec = 1000 millisecond
import 'package:flutter/material.dart';
import 'package:vibration/vibration.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Home(),
);
}
}
class Home extends StatelessWidget{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Device Vibration with Flutter"),
backgroundColor: Colors.redAccent,
),
body: Container(
padding: EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Container(
alignment: Alignment.center,
padding: EdgeInsets.all(5),
child: ElevatedButton(
child: Text("Vibrate Default"),
onPressed: () async {
if (await Vibration.hasVibrator()) { //check if device has vibration feature
Vibration.vibrate(); //500 millisecond vibration
}
},
),
),
Container(
alignment: Alignment.center,
padding: EdgeInsets.all(5),
child: ElevatedButton(
child: Text("Vibrate For 1 Sec"),
onPressed: (){
Vibration.vibrate(duration: 1000); //1 Sec = 1000 millisecond
},
),
),
Container(
alignment: Alignment.center,
padding: EdgeInsets.all(5),
child: ElevatedButton(
child: Text("Vibrate With Pattern"),
onPressed: (){
Vibration.vibrate(
pattern: [
500, //wait 0.5 second
1000, //vibrate 1 second
500, //wait 0.5 second
3000 //vibrate 3 second.
//add mroe pattern here
]
); //1 Sec = 1000 millisecond
},
),
)
],)
),
);
}
}
In this way, you can vibrate device programmatically with Dart in Flutter App.
Please Wait...
No any Comments on this Article