Push-up Counter using Proximity Sensor in Flutter

Create a counter using Flutter. Count the pushup number using proximity sensor. And use a library to access the sensor.
featured image
profile_image
Tasnim Zotder
May 11, 2022
⏱️ 2 Minutes

Code

Add the counter

include the material library

import 'package:flutter/material.dart';

Inside the class, declare the counter variable and display it -

int _counter = 0;

...

Text('$_counter'),

Now run the project, it'll display the counter value 0.

the full code -

import 'package:flutter/material.dart';

void main() {
  runApp(const PushupCounter());
}

class PushupCounter extends StatefulWidget {
  const PushupCounter({Key? key}) : super(key: key);

  @override
  State<PushupCounter> createState() => _PushupCounterState();
}

class _PushupCounterState extends State<PushupCounter> {
  int _counter = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: const Text('Pushup Counter'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '$_counter',
              style: const TextStyle(fontSize: 44.0),
            ),
            const Text("Pushups Count"),
          ],
        ),
      ),
    ));
  }
}

Add & import the library

add the proximity_sensor library by running the following command in the terminal -

flutter pub add proximity_sensor

include the library in the project

import 'package:proximity_sensor/proximity_sensor.dart';

also include the async library

import 'dart:async';

Add the proximity sensor

read from the proximity sensor

  bool _isNear = false;
  bool _currState = false;
  late StreamSubscription<dynamic> _streamSubscription;

  ...

  void updateCounter() {
    if (_isNear == true && _currState == false) {
      setState(() {
        _counter++;
        _currState = true;
      });
    } else if (_isNear == false && _currState == true) {
      setState(() {
        _currState = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    listenToSensor();
  }

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

  Future<void> listenToSensor() async {
    FlutterError.onError = (FlutterErrorDetails details) {
      if (foundation.kDebugMode) {
        FlutterError.dumpErrorToConsole(details);
      }
    };

    _streamSubscription = ProximitySensor.events.listen((int event) {
      setState(() {
        _isNear = (event > 0) ? true : false;
      });
      updateCounter();
    });
  }

The Complete Code

import 'package:flutter/material.dart';
import 'package:proximity_sensor/proximity_sensor.dart';
import 'package:flutter/foundation.dart' as foundation;
import 'dart:async';

void main() {
  runApp(const PushupCounter());
}

class PushupCounter extends StatefulWidget {
  const PushupCounter({Key? key}) : super(key: key);

  @override
  State<PushupCounter> createState() => _PushupCounterState();
}

class _PushupCounterState extends State<PushupCounter> {
  int _counter = 0;

  bool _isNear = false;
  bool _currState = false;
  late StreamSubscription<dynamic> _streamSubscription;

  @override
  void initState() {
    super.initState();
    listenToSensor();
  }

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

  void updateCounter() {
    if (_isNear == true && _currState == false) {
      setState(() {
        _counter++;
        _currState = true;
      });
    } else if (_isNear == false && _currState == true) {
      setState(() {
        _currState = false;
      });
    }
  }

  Future<void> listenToSensor() async {
    FlutterError.onError = (FlutterErrorDetails details) {
      if (foundation.kDebugMode) {
        FlutterError.dumpErrorToConsole(details);
      }
    };

    _streamSubscription = ProximitySensor.events.listen((int event) {
      setState(() {
        _isNear = (event > 0) ? true : false;
      });
      updateCounter();
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      appBar: AppBar(
        title: const Text('Pushup Counter'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '$_counter',
              style: const TextStyle(fontSize: 44.0),
            ),
            Text('$_isNear'),
            const Text("Pushups Count"),
          ],
        ),
      ),
    ));
  }
}
;
Contents
  • Blog
  • YouTube
Personal
  • Portfolio

github
twitter
linkedin
youtube
© Tasnim Zotder | 2022
🏡
Home
📝
Blog
💡
Portfolio