How To Use Accelerometer Sensor Using Flutter Android App

admin_img Posted By Bajarangi soft , Posted On 06-11-2020

I recently wanted to create a simple game for my Drink Counter app that made use of the device’s accelerometer. Here is what I learned.

How To Use Accelerometer Sensor Using Flutter Android App

Accelerometer Sensor
Step 1
We cannot directly remove the time stamp from Accelerometer Sensor
 but using the intl.dart package we can easily filter the date stamp from time stamp. So open your flutter project’s pubspec.yaml in code .

dependencies:
  flutter:
    sdk: flutter
  sensors: ^0.4.2+6

Step 2
After done saving the pubspec.yaml file, Open your flutter project root folder in Command Prompt or Terminal and execute flutter pub get command. 
flutter pub get

Step 3
 Open your project’s main.dart file and import material.dart  package.
import 'dart:math'; 
import 'package:flutter/cupertino.dart'; 
import 'package:flutter/material.dart'; 
import 'package:sensors/sensors.dart';
import 'dart:async';

Complete Code For Accelerometer Sensor In Flutter
main.dart
import 'dart:math';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:sensors/sensors.dart';
import 'dart:async';

void main() => runApp(MyApp());

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

MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Color color = Colors.orange;
  AccelerometerEvent event;
  Timer timer;
  StreamSubscription accel;
  double top = 125;
  double left;
  int count = 0;
  double width;
  double height;

  setColor(AccelerometerEvent event) {
    double x = ((event.x * 12) + ((width - 100) / 2));
    double y = event.y * 12 + 125;
    var xDiff = x.abs() - ((width - 100) / 2);
    var yDiff = y.abs() - 125;
    if (xDiff.abs() < 3 && yDiff.abs() < 3) {
      setState(() {
        color = Colors.blue[100];
        count += 2;
      });
    } else {
      setState(() {
        color = Colors.red;
        count = 0;
      });
    }
  }

  setPosition(AccelerometerEvent event) {
    if (event == null) {
      return;
    }
    setState(() {
      left = ((event.x * 12) + ((width - 100) / 2));
    });
    setState(() {
      top = event.y * 12 + 125;
    });
  }

  startTimer() {
    if (accel == null) {
      accel = accelerometerEvents.listen((AccelerometerEvent eve) {
        setState(() {
          event = eve;
        });
      });
    } else {
      accel.resume();
    }
    if (timer == null || !timer.isActive) {
      timer = Timer.periodic(Duration(milliseconds: 200), (_) {
        if (count > 3) {
          pauseTimer();
        } else {
          setColor(event);
          setPosition(event);
        }
      });
    }
  }

  pauseTimer() {
    timer.cancel();
    accel.pause();
    setState(() {
      count = 0;
      color = Colors.blue[900];
    });
  }

  @override
  void dispose() {
    timer?.cancel();
    accel?.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    width = MediaQuery.of(context).size.width;
    height = MediaQuery.of(context).size.height;

    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.red[800],
        title: Text(' Accelerometer Sensor'),
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text('Keep the circle in the center for 1 second'),
          ),
          Stack(
            children: [
              Container(
                height: height / 2,
                width: width,
              ),
              Positioned(
                top: 50,
                left: (width - 250) / 2,
                child: Container(
                  height: 250,
                  width: 250,
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.red, width: 2.0),
                    borderRadius: BorderRadius.circular(125),
                  ),
                ),
              ),
              Positioned(
                top: top,
                left: left ?? (width - 100) / 2,
                child: ClipOval(
                  child: Container(
                    width: 100,
                    height: 100,
                    color: color,
                  ),
                ),
              ),
              Positioned(
                top: 125,
                left: (width - 100) / 2,
                child: Container(
                  height: 100,
                  width: 100,
                  decoration: BoxDecoration(
                    border: Border.all(color: Colors.blue, width: 2.0),
                    borderRadius: BorderRadius.circular(50),
                  ),
                ),
              ),
            ],
          ),
          Text('x: ${(event?.x ?? 0).toStringAsFixed(3)}'),
          Text('y: ${(event?.y ?? 0).toStringAsFixed(3)}'),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
            child: RaisedButton(
              onPressed: startTimer,
              child: Text('Begin'),
              color: Colors.red[800],
              textColor: Colors.white,
            ),
          )
        ],
      ),
    );
  }
}

Related Post