Flutter Sensors

Flutter Sensors:

A Flutter used to access the accelerometer and gyroscope sensors.

What are Accelerometer Sensors:

An accelerometer is a tool that measures the proper acceleration of a device. Proper acceleration is the acceleration i.e the rate of change of velocity of a device in its own instantaneous rest frame.

For example, an accelerometer at rest on the surface of the Earth will measure an acceleration due to Earth’s gravity.

The Accelerometer tells whether the device is moving or not if moving in which direction it is moving.

 

What are Gyroscope Sensors:

A gyroscope sensor is a device used for measuring or maintaining orientation and angular velocity. It is a spinning wheel or disc in which the axis of rotation is free to assume any orientation by itself.

Gyroscope sensors are used to find the orientation of the device that is portrait or landscape.

Using the Sensors in Flutter App:

To use the sensors in the Flutter App following the below steps:

Add the dependency package:

adding the dependency package to pubspec.yaml file. use the below code to add the dependency package. After adding the dependency package run the get package method to import all the required files to the app.

 

dependencies:
sensors: ^0.4.2+6

Install the package:

You can install the package from the command line using the below code with Flutter as shown.

$ flutter pub get

Importing the Package:

Adding the dependency package to the pubspec.yaml file , you can now import the package into the dart code by using the below code. without adding the dependency packge to the pubspec.yaml file if you import it will show package not found an error.

import 'package:sensors/sensors.dart';

The Flutter Sensors have the three classes of sensor events, with three different streams.

  • AccelerometerEvents describe the velocity of the device with gravity. You can use accelerometer readings to tell if the device is moving in a particular direction.
  • UserAccelerometerEvents also describe the velocity of the device without gravity. 
  • GyroscopeEvents are used to describe the rotation of the device.

 

Complete example code for Flutter Sensors:

Copy and paste the below code into your main.dart

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

import 'snake.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Sensors Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

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

final String title;

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

class _MyHomePageState extends State {
static const int _snakeRows = 20;
static const int _snakeColumns = 20;
static const double _snakeCellSize = 10.0;

List _accelerometerValues;
List _userAccelerometerValues;
List _gyroscopeValues;
List> _streamSubscriptions =
>[];

@override
Widget build(BuildContext context) {
final List accelerometer =
_accelerometerValues?.map((double v) => v.toStringAsFixed(1))?.toList();
final List gyroscope =
_gyroscopeValues?.map((double v) => v.toStringAsFixed(1))?.toList();
final List userAccelerometer = _userAccelerometerValues
?.map((double v) => v.toStringAsFixed(1))
?.toList();

return Scaffold(
appBar: AppBar(
title: const Text('Sensor Example'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Center(
child: DecoratedBox(
decoration: BoxDecoration(
border: Border.all(width: 1.0, color: Colors.black38),
),
child: SizedBox(
height: _snakeRows * _snakeCellSize,
width: _snakeColumns * _snakeCellSize,
child: Snake(
rows: _snakeRows,
columns: _snakeColumns,
cellSize: _snakeCellSize,
),
),
),
),
Padding(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Accelerometer: $accelerometer'),
],
),
padding: const EdgeInsets.all(16.0),
),
Padding(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('UserAccelerometer: $userAccelerometer'),
],
),
padding: const EdgeInsets.all(16.0),
),
Padding(
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text('Gyroscope: $gyroscope'),
],
),
padding: const EdgeInsets.all(16.0),
),
],
),
);
}

@override
void dispose() {
super.dispose();
for (StreamSubscription subscription in _streamSubscriptions) {
subscription.cancel();
}
}

@override
void initState() {
super.initState();
_streamSubscriptions
.add(accelerometerEvents.listen((AccelerometerEvent event) {
setState(() {
_accelerometerValues = [event.x, event.y, event.z];
});
}));
_streamSubscriptions.add(gyroscopeEvents.listen((GyroscopeEvent event) {
setState(() {
_gyroscopeValues = [event.x, event.y, event.z];
});
}));
_streamSubscriptions
.add(userAccelerometerEvents.listen((UserAccelerometerEvent event) {
setState(() {
_userAccelerometerValues = [event.x, event.y, event.z];
});
}));
}
}

we have imported snake.dart in main.dart file

place the two files in the same location that is in lib. 

create a snake.dart file paste the below code into that and import it into main.dart file 

snake.dart

snake.dart

import 'dart:async';
import 'dart:math' as math;

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

class Snake extends StatefulWidget {
Snake({this.rows = 20, this.columns = 20, this.cellSize = 10.0}) {
assert(10 <= rows); assert(10 <= columns); assert(5.0 <= cellSize); } final int rows; final int columns; final double cellSize; @override State createState() => SnakeState(rows, columns, cellSize);
}

class SnakeBoardPainter extends CustomPainter {
SnakeBoardPainter(this.state, this.cellSize);

GameState state;
double cellSize;

@override
void paint(Canvas canvas, Size size) {
final Paint blackLine = Paint()..color = Colors.black;
final Paint blackFilled = Paint()
..color = Colors.black
..style = PaintingStyle.fill;
canvas.drawRect(
Rect.fromPoints(Offset.zero, size.bottomLeft(Offset.zero)),
blackLine,
);
for (math.Point p in state.body) {
final Offset a = Offset(cellSize * p.x, cellSize * p.y);
final Offset b = Offset(cellSize * (p.x + 1), cellSize * (p.y + 1));

canvas.drawRect(Rect.fromPoints(a, b), blackFilled);
}
}

@override
bool shouldRepaint(CustomPainter oldDelegate) {
return true;
}
}

class SnakeState extends State {
SnakeState(int rows, int columns, this.cellSize) {
state = GameState(rows, columns);
}

double cellSize;
GameState state;
AccelerometerEvent acceleration;
StreamSubscription _streamSubscription;
Timer _timer;

@override
Widget build(BuildContext context) {
return CustomPaint(painter: SnakeBoardPainter(state, cellSize));
}

@override
void dispose() {
super.dispose();
_streamSubscription.cancel();
_timer.cancel();
}

@override
void initState() {
super.initState();
_streamSubscription =
accelerometerEvents.listen((AccelerometerEvent event) {
setState(() {
acceleration = event;
});
});

_timer = Timer.periodic(const Duration(milliseconds: 200), (_) {
setState(() {
_step();
});
});
}

void _step() {
final math.Point newDirection = acceleration == null
? null
: acceleration.x.abs() < 1.0 && acceleration.y.abs() < 1.0 ? null : (acceleration.x.abs() < acceleration.y.abs()) ? math.Point(0, acceleration.y.sign.toInt())
: math.Point(-acceleration.x.sign.toInt(), 0);
state.step(newDirection);
}
}

class GameState {
GameState(this.rows, this.columns) {
snakeLength = math.min(rows, columns) - 5;
}

int rows;
int columns;
int snakeLength;

List> body = >[const math.Point(0, 0)];
math.Point direction = const math.Point(1, 0);

void step(math.Point newDirection) {
math.Point next = body.last + direction;
next = math.Point(next.x % columns, next.y % rows);

body.add(next);
if (body.length > snakeLength) body.removeAt(0);
direction = newDirection ?? direction;
}
}

Congratulations You Have Learned to Use Sensors in Flutter ….!!!

If It Is Helpful Share It With Your Friends….!!!

Leave a Reply

Categories