Open In App

Flutter – Using Accelerometer Sensor

Last Updated : 19 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to make an app that will fetch the data from the Accelerometer sensor and display it. To access the accelerometer we take the help of the sensors_plus package. The app uses the sensors_plus package to access accelerometer data. In this specific example, it uses the accelerometer events using _accelerometerSubscription. when we move the device the accelerometer value will change and it will fetch the data and Display it. A sample video is given below to get an idea about what we are going to do in this article.

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package

First of all import material.dart , dart:async and sensors_plus.dart packages.

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:sensors_plus/sensors_plus.dart';

Step 3: Execute the main Method

Here the execution of our app starts.

Dart




void main() {
  runApp(MyApp());
}


Step 4: Create MyApp Class

In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.

Dart




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false,
      home: AccelerometerExample(),
    );
  }
}


Step 5: Create AccelerometerExample Class

In this class we are going to use the Accelerometer to know the device position in X,Y,Z coordinates by using sensors_plus package.

  • The app uses the sensors_plus package to access accelerometer data. In this specific example, it subscribes to the accelerometer events using _accelerometerSubscription.
  • When accelerometer data is received, it updates the state of the app with the new data. This is done inside the callback function passed to accelerometerEvents.listen().
  • The accelerometer data includes three values: X, Y, and Z, which represent the acceleration along the respective axes.
  • The app continuously updates the UI with the latest accelerometer data.
  • If there’s no accelerometer data available means the device does not have accelerometer sensor then , it displays “No data available.”

Dart




class AccelerometerExample extends StatefulWidget {
  const AccelerometerExample({super.key});
  
  @override
  State<AccelerometerExample> createState() => _AccelerometerExampleState();
}
  
class _AccelerometerExampleState extends State<AccelerometerExample> {
  // List to store accelerometer data
  List<AccelerometerEvent> _accelerometerValues = [];
  
  // StreamSubscription for accelerometer events
  late StreamSubscription<AccelerometerEvent> _accelerometerSubscription;
  
  @override
  void initState() {
    super.initState();
  
    // Subscribe to accelerometer events
    _accelerometerSubscription = accelerometerEvents.listen((event) {
      setState(() {
        // Update the _accelerometerValues list with the latest event
        _accelerometerValues = [event];
      });
    });
  }
  
  @override
  void dispose() {
    // Cancel the accelerometer event subscription to prevent memory leaks
    _accelerometerSubscription.cancel();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Accelerometer Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Accelerometer Data:',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 10),
            if (_accelerometerValues.isNotEmpty)
              Text(
                'X: ${_accelerometerValues[0].x.toStringAsFixed(2)}, '
                'Y: ${_accelerometerValues[0].y.toStringAsFixed(2)}, '
                'Z: ${_accelerometerValues[0].z.toStringAsFixed(2)}',
                style: TextStyle(fontSize: 16),
              )
            else
              Text('No data available', style: TextStyle(fontSize: 16)),
          ],
        ),
      ),
    );
  }
}


Here is the full Code of main.dart file

Dart




import 'dart:async';
import 'package:flutter/material.dart';
import 'package:sensors_plus/sensors_plus.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.green, // Set the app's primary theme color
      ),
      debugShowCheckedModeBanner: false,
      home: AccelerometerExample(),
    );
  }
}
  
class AccelerometerExample extends StatefulWidget {
  const AccelerometerExample({super.key});
  
  @override
  State<AccelerometerExample> createState() => _AccelerometerExampleState();
}
  
class _AccelerometerExampleState extends State<AccelerometerExample> {
  // List to store accelerometer data
  List<AccelerometerEvent> _accelerometerValues = [];
  
  // StreamSubscription for accelerometer events
  late StreamSubscription<AccelerometerEvent> _accelerometerSubscription;
  
  @override
  void initState() {
    super.initState();
  
    // Subscribe to accelerometer events
    _accelerometerSubscription = accelerometerEvents.listen((event) {
      setState(() {
        // Update the _accelerometerValues list with the latest event
        _accelerometerValues = [event];
      });
    });
  }
  
  @override
  void dispose() {
    // Cancel the accelerometer event subscription to prevent memory leaks
    _accelerometerSubscription.cancel();
    super.dispose();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Accelerometer Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Accelerometer Data:',
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(height: 10),
            if (_accelerometerValues.isNotEmpty)
              Text(
                'X: ${_accelerometerValues[0].x.toStringAsFixed(2)}, '
                'Y: ${_accelerometerValues[0].y.toStringAsFixed(2)}, '
                'Z: ${_accelerometerValues[0].z.toStringAsFixed(2)}',
                style: TextStyle(fontSize: 16),
              )
            else
              Text('No data available', style: TextStyle(fontSize: 16)),
          ],
        ),
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads