accurate_step_counter 1.8.0 copy "accurate_step_counter: ^1.8.0" to clipboard
accurate_step_counter: ^1.8.0 copied to clipboard

A highly accurate step counter plugin using accelerometer-based detection with low-pass filtering and peak detection. Includes Hive database logging with warmup validation. Supports foreground, backgr [...]

Accurate Step Counter #

pub package License: MIT Tests Production Ready

A simple, accurate step counter for Flutter. Works in foreground, background, and terminated states. Health Connect-like API with persistent storage.

โœจ Features #

  • ๐ŸŽฏ Accurate - Uses sensors_plus accelerometer with peak detection algorithm
  • ๐Ÿ’พ Persistent - Steps saved to local DB (Hive)
  • ๐Ÿ“ฑ All States - Foreground, background, AND terminated
  • ๐Ÿš€ Simple API - One-line setup, no complexity
  • ๐Ÿ”‹ Battery Efficient - Event-driven, not polling
  • โฑ๏ธ Inactivity Timeout - Auto-reset sessions after idle periods
  • ๐ŸŒ External Import - Import steps from Google Fit, Apple Health, etc.
  • ๐Ÿงช Well Tested - 671 automated tests covering all scenarios

๐Ÿ“ฑ Platform Support #

Platform Status
Android โœ… Full support (API 19+)
iOS โŒ Not supported

๐Ÿš€ Quick Start #

1. Install #

dependencies:
  accurate_step_counter: ^1.8.0

2. Add Permissions #

In android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_HEALTH"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

3. Use It! #

import 'package:accurate_step_counter/accurate_step_counter.dart';

final stepCounter = AccurateStepCounter();

// ๐Ÿš€ One-line setup!
await stepCounter.initSteps();

// Get today's steps
final todaySteps = await stepCounter.getTodayStepCount();

// Watch real-time updates
stepCounter.watchTodaySteps().listen((steps) {
  print('Steps today: $steps');
});

// Get yesterday's steps
final yesterdaySteps = await stepCounter.getYesterdayStepCount();

// Custom date range
final weekSteps = await stepCounter.getStepCount(
  start: DateTime.now().subtract(Duration(days: 7)),
  end: DateTime.now(),
);

๐Ÿ“– Complete Example #

import 'package:flutter/material.dart';
import 'package:accurate_step_counter/accurate_step_counter.dart';
import 'package:permission_handler/permission_handler.dart';

class StepCounterPage extends StatefulWidget {
  @override
  State<StepCounterPage> createState() => _StepCounterPageState();
}

class _StepCounterPageState extends State<StepCounterPage> 
    with WidgetsBindingObserver {
  final _stepCounter = AccurateStepCounter();
  int _steps = 0;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _init();
  }

  Future<void> _init() async {
    // Request permissions
    await Permission.activityRecognition.request();
    
    // Initialize step counter
    await _stepCounter.initSteps();
    
    // Watch today's steps (emits immediately with stored value!)
    _stepCounter.watchTodaySteps().listen((steps) {
      setState(() => _steps = steps);
    });
    
    // Handle terminated state sync
    _stepCounter.onTerminatedStepsDetected = (steps, from, to) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(content: Text('Synced $steps missed steps!')),
      );
    };
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    _stepCounter.setAppState(state); // Important for source tracking!
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _stepCounter.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text('$_steps steps', style: TextStyle(fontSize: 48)),
      ),
    );
  }
}

๐Ÿ”ง API Reference #

Core Methods #

Method Description
initSteps() One-line setup (DB + detector + logging)
getTodayStepCount() Get today's total steps
getYesterdayStepCount() Get yesterday's total steps
getStepCount(start, end) Get steps for date range
watchTodaySteps() Real-time stream of today's steps
setAppState(state) Track foreground/background (call in didChangeAppLifecycleState)
dispose() Clean up resources

Reading Logs #

// Get all step logs with details
final logs = await stepCounter.getStepLogs();

for (final log in logs) {
  print('${log.stepCount} steps');
  print('From: ${log.fromTime} To: ${log.toTime}');
  print('Source: ${log.source}'); // foreground, background, terminated, external
}

// Filter by date or source
final todayLogs = await stepCounter.getStepLogs(from: startOfToday);
final bgLogs = await stepCounter.getStepLogs(source: StepRecordSource.background);
final externalLogs = await stepCounter.getStepLogs(source: StepRecordSource.external);

// Get stats
final stats = await stepCounter.getStepStats();
// {totalSteps, foregroundSteps, backgroundSteps, terminatedSteps, ...}

Importing External Steps (NEW in v1.6.0) #

// Import steps from Google Fit, Apple Health, wearables, etc.
await stepCounter.writeStepsToAggregated(
  stepCount: 500,
  fromTime: DateTime.now().subtract(Duration(hours: 2)),
  toTime: DateTime.now(),
  source: StepRecordSource.external, // Mark as external import
);
// All listeners automatically notified!

// Query external steps
final externalSteps = await stepCounter.getStepsBySource(
  StepRecordSource.external,
);

Data Management #

// Clear all logs
await stepCounter.clearStepLogs();

// Delete old logs
await stepCounter.deleteStepLogsBefore(
  DateTime.now().subtract(Duration(days: 30)),
);

๐Ÿ“ฑ How It Works (Hybrid Architecture v1.8.x) #

App State Android โ‰ค10 (API โ‰ค29) Android 11+ (API 30+)
๐ŸŸข Foreground sensors_plus accelerometer (realtime) Native detector (realtime)
๐ŸŸก Background sensors_plus accelerometer (realtime) Native detector (realtime)
๐Ÿ”ด Terminated Foreground service with sensors_plus TYPE_STEP_COUNTER sync on restart

Key Benefits (v1.8.0):

  • โœ… More Reliable: sensors_plus provides consistent accelerometer access across devices
  • โœ… Better UX: No persistent notification when app is running (Android 11+)
  • โœ… Better battery: Foreground service only runs when needed (terminated state on Android โ‰ค10)
  • โœ… Realtime updates: Instant step feedback in all running states
  • โœ… No duplicates: Smart duplicate prevention prevents double-counting on rapid restarts
  • โœ… OEM Compatible: Works reliably on MIUI, Samsung, and other aggressive battery optimization systems

sensors_plus Step Detection Algorithm:

  • Low-pass filter for noise reduction
  • Peak detection with configurable threshold
  • Minimum time between steps enforcement
  • Configurable via StepDetectorConfig

โš™๏ธ Advanced Configuration #

For more control, use the advanced setup:

// Initialize database
await stepCounter.initializeLogging(debugLogging: true);

// Start with custom config
await stepCounter.start(
  config: StepDetectorConfig(
    enableOsLevelSync: true,
    useForegroundServiceOnOldDevices: true,
    foregroundServiceMaxApiLevel: 29, // Use service on Android โ‰ค10
  ),
);

// Start logging with preset
await stepCounter.startLogging(config: StepRecordConfig.walking());
// Presets: walking(), running(), sensitive(), conservative(), aggregated()

// Custom config with inactivity timeout (NEW in v1.6.0)
await stepCounter.startLogging(
  config: StepRecordConfig.walking().copyWith(
    inactivityTimeoutMs: 10000, // Reset after 10s of no steps
  ),
);

๐Ÿงช Testing #

The package includes 671 automated tests covering all scenarios:

# Run all tests
flutter test

# Expected output: 00:02 +671: All tests passed!

Test Coverage #

Category Tests
Foreground State 100+
Background State 100+
Terminated State 100+
Duplicate Prevention 100+
State Transitions 60+
API Level Tests 50+
Edge Cases 50+
Config & Parameters 100+

โœ… Production Readiness #

This package is production ready with:

  • โœ… 671 automated tests
  • โœ… Works on all Android versions (API 19+)
  • โœ… OEM compatible (MIUI, Samsung, etc.)
  • โœ… Battery efficient
  • โœ… No duplicate step counting
  • โœ… Handles all app states
  • โœ… Well documented API

๐Ÿ“„ License #

MIT License - see LICENSE

1
likes
0
points
1.44k
downloads

Publisher

verified publisherrahulsha.com.np

Weekly Downloads

A highly accurate step counter plugin using accelerometer-based detection with low-pass filtering and peak detection. Includes Hive database logging with warmup validation. Supports foreground, background, and terminated state tracking.

Repository (GitHub)
View/report issues

Documentation

Documentation

License

unknown (license)

Dependencies

flutter, hive, hive_flutter, sensors_plus

More

Packages that depend on accurate_step_counter

Packages that implement accurate_step_counter