Sensors
1. Accelerometer
This listens to the device's acceleration along the x, y, and z axes, including gravity.
import 'package:sensors_plus/sensors_plus.dart';
void listenToAccelerometer() {
accelerometerEvents.listen(
(AccelerometerEvent event) {
print(event);
},
onError: (error) {
// Logic to handle error
// Needed for Android in case the sensor is not available
},
cancelOnError: true,
);
}
// Output Example: [AccelerometerEvent (x: 0.0, y: 9.8, z: 0.0)]
Error Handling
Each listener includes:
onError:
o Handles scenarios where the sensor might not be available (e.g., on certain
devices or platforms).
cancelOnError:
o Ensures the listener stops listening to the stream when an error occurs.
2. User Accelerometer
This listens to the device's acceleration along the x, y, and z axes, excluding gravity.
import 'package:sensors_plus/sensors_plus.dart';
void listenToUserAccelerometer() {
userAccelerometerEvents.listen(
(UserAccelerometerEvent event) {
print(event);
},
onError: (error) {
// Logic to handle error
// Needed for Android in case the sensor is not available
},
cancelOnError: true,
);
}
// Output Example: [UserAccelerometerEvent (x: 0.0, y: 0.0, z: 0.0)]
3. Gyroscope
This listens to the device's rotation rate around the x, y, and z axes.
import 'package:sensors_plus/sensors_plus.dart';
void listenToGyroscope() {
gyroscopeEvents.listen(
(GyroscopeEvent event) {
print(event);
},
onError: (error) {
// Logic to handle error
// Needed for Android in case the sensor is not available
},
cancelOnError: true,
);
}
// Output Example: [GyroscopeEvent (x: 0.0, y: 0.0, z: 0.0)]
4. Magnetometer
This listens to the device's magnetic field strength along the x, y, and z axes.
import 'package:sensors_plus/sensors_plus.dart';
void listenToMagnetometer() {
magnetometerEvents.listen(
(MagnetometerEvent event) {
print(event);
},
onError: (error) {
// Logic to handle error
// Needed for Android in case the sensor is not available
},
cancelOnError: true,
);
}
// Output Example: [MagnetometerEvent (x: -23.6, y: 6.2, z: -34.9)]
5. Barometer
This listens to the device's atmospheric pressure.
import 'package:sensors_plus/sensors_plus.dart';
void listenToBarometer() {
barometerEvents.listen(
(BarometerEvent event) {
print(event);
},
onError: (error) {
// Logic to handle error
// Needed for Android in case the sensor is not available
},
cancelOnError: true,
);
}
// Output Example: [BarometerEvent (pressure: 1000.0)]
Usage
You can call the specific functions in your Flutter app depending on which sensor data
you want to access:
void main() {
listenToAccelerometer();
listenToUserAccelerometer();
listenToGyroscope();
listenToMagnetometer();
listenToBarometer();
}
Each function is modular and handles a single sensor, making the code easy to maintain
and debug.
Sensor Calibration Example
import 'package:sensors_plus/sensors_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
// Class to handle sensor calibration logic
class SensorCalibration {
// Variables to store calibration offsets for accelerometer
axes
double? accelerometerOffsetX;
double? accelerometerOffsetY;
double? accelerometerOffsetZ;
// Method to check if the sensor has already been calibrated
Future<bool> checkCalibrationStatus() async {
// Access the SharedPreferences instance
SharedPreferences prefs = await
SharedPreferences.getInstance();
// Check if the calibration status is saved in
SharedPreferences
// If it is null, return false (sensor is not calibrated)
return prefs.getBool('isCalibrated') ?? false;
// Method to perform sensor calibration
Future<void> calibrateSensor() async {
// Lists to store accelerometer readings for calibration
List<double> accelXReadings = [];
List<double> accelYReadings = [];
List<double> accelZReadings = [];
// Listen to accelerometer events
accelerometerEvents.listen(
(AccelerometerEvent event) {
// Add readings from the accelerometer to the lists
accelXReadings.add(event.x);
accelYReadings.add(event.y);
accelZReadings.add(event.z);
// Stop collecting data once 100 readings are gathered
if (accelXReadings.length > 100) {
accelerometerEvents.drain(); // Stop listening to the
stream
// Calculate the average of the readings to determine the
offset
accelerometerOffsetX = accelXReadings.reduce((a, b) => a
+ b) / accelXReadings.length;
accelerometerOffsetY = accelYReadings.reduce((a, b) => a
+ b) / accelYReadings.length;
accelerometerOffsetZ = accelZReadings.reduce((a, b) => a
+ b) / accelZReadings.length;
// Save the calculated offsets to persistent storage
_saveCalibrationData();
},
onError: (error) => print(error), // Handle errors in case
the sensor is not available
cancelOnError: true, // Stop listening on error
);
// Method to save calibration data to persistent storage
Future<void> _saveCalibrationData() async {
// Access the SharedPreferences instance
SharedPreferences prefs = await
SharedPreferences.getInstance();
// Save calibration status and offsets to SharedPreferences
prefs.setBool('isCalibrated', true); // Mark the sensor as
calibrated
prefs.setDouble('accelerometerOffsetX',
accelerometerOffsetX!);
prefs.setDouble('accelerometerOffsetY',
accelerometerOffsetY!);
prefs.setDouble('accelerometerOffsetZ',
accelerometerOffsetZ!);
// Method to get calibrated accelerometer data by subtracting
offsets from raw data
Future<AccelerometerEvent> getCalibratedAccelerometerData()
async {
// Transform raw accelerometer events to account for
calibration offsets
return accelerometerEvents.map((event) {
return AccelerometerEvent(
event.x - accelerometerOffsetX!, // Adjust x-axis data
event.y - accelerometerOffsetY!, // Adjust y-axis data
event.z - accelerometerOffsetZ!, // Adjust z-axis data
event.timestamp, // Retain the original timestamp
);
}).first; // Return the first event from the transformed
stream
}
Location Code
import 'package:location/location.dart';
// Create a Location instance to access location services
Location location = new Location();
// Declare variables to manage the service status and permission
status
bool _serviceEnabled; // To check if location services are
enabled on the device
PermissionStatus _permissionGranted; // To check if the app has
location permissions
LocationData _locationData; // To store the location data
retrieved from the device
// Step 1: Check if location services are enabled
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
// If location services are not enabled, request the user to
enable them
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
// If the user declines to enable location services, exit the
function
return;
}
// Step 2: Check if the app has location permissions
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
// If permission is denied, request the user to grant
permission
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
// If the user does not grant permission, exit the function
return;
// Step 3: Retrieve the current location data
_locationData = await location.getLocation();
GeoLocation Code
import 'package:geolocator/geolocator.dart';
Future<Position> getCurrentPositionGeolocator() async{
bool isServiceEnabled = false;
LocationPermission isPermissionGranted;
// Checking is service enabled
isServiceEnabled = await Geolocator.isLocationServiceEnabled();
if(!isServiceEnabled){
return Future.error('Location services are disabled');
// Checking for location denied permissions
isPermissionGranted = await Geolocator.checkPermission();
if(isPermissionGranted == LocationPermission.denied){
// Handle permission issue -- it was mentioned that you could
ask for permissions again
while(isPermissionGranted == LocationPermission.denied){
isPermissionGranted = await Geolocator.requestPermission();
// Checking for location denied forever permission
if(isPermissionGranted == LocationPermission.deniedForever){
// Handle permission
return Future.error('Location permissions is denied
forever');
}
// Now returning the current position
// return Geolocator.getCurrentPosition();
// LocationAccuracy. => high - low - medium - best -
bestForNavigation
return Geolocator.getCurrentPosition(desiredAccuracy:
LocationAccuracy.high);