How to Get Gyroscope Sensor Data in Flutter App

In this example, we are going to show you how to get data of the Gyroscope sensor of the device in the Flutter App. You can stream constantly the Gyroscope sensor data too. You will get X, Y, Z values which can be used to determine the device orientation. See the example below:

First, add sensor_plus package in your project by adding the following lines in pubspec.yaml file.

dependencies:
  flutter:
    sdk: flutter
  sensors_plus: ^1.2.2

Now, import the sensor_plus package in your script:

import 'package:sensors_plus/sensors_plus.dart';

Now add the stream subscription to get Gyroscope data constantly:

gyroscopeEvents.listen((GyroscopeEvent event) {
   print(event);
   //Output: [GyroscopeEvent (x: 0.08372224867343903, y: -0.09925820678472519, z: 0.21376553177833557)]
});

You can use this data to determine the orientation of your device.

Image Source: MathWorks.com, you can see Gyroscope details too.

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


Future<void> main() async {
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatefulWidget{
  @override
  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {

  double x = 0, y = 0, z = 0;
  String direction = "none";

  @override
  void initState() {
    gyroscopeEvents.listen((GyroscopeEvent event) {
       print(event);

       x = event.x;
       y = event.y;
       z = event.z;

       //rough calculation, you can use 
       //advance formula to calculate the orentation
       if(x > 0){ 
           direction = "back";
       }else if(x < 0){
           direction = "forward";
       }else if(y > 0){
           direction = "left";
       }else if(y < 0){
           direction = "right";
       }

       setState(() {
         
       });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) { 
    return  Scaffold(
          appBar: AppBar( 
              title: Text("Gyroscope Sensor in Flutter"),
              backgroundColor: Colors.redAccent,
          ),
          body: Container( 
            alignment: Alignment.center,
            padding: EdgeInsets.all(30),
            child: Column(
               children:[
                   Text(direction, style: TextStyle(fontSize: 30),)
               ]
            )
          ),
           
       );
  }
}

Here, we have a subscription from the Gyroscope sensor, and after getting the data, we have done very surface calculations to determine the orientation of the device.

In this way, you can get the gyroscope sensor data from device in Flutter app.

No any Comments on this Article


Please Wait...