locus library

Locus - Background geolocation SDK for Flutter.

A pure, unopinionated foundation for background location tracking with native geofencing, activity recognition, and HTTP sync capabilities.

Quick Start

import 'package:locus/locus.dart';

// Initialize with defaults
await Locus.ready();

// Start tracking
await Locus.start();

// Listen to location updates
Locus.onLocation((location) {
  print('${location.coords.latitude}, ${location.coords.longitude}');
});

Philosophy

Locus provides building blocks, not business logic. Your app composes these primitives into your specific solution (fleet, fitness, social, etc.)

Classes

Activity
AdaptiveSettings
Calculated adaptive settings based on current conditions.
AdaptiveTrackingConfig
Configuration for adaptive tracking behavior.
Battery
BatteryBenchmark
Benchmark session for measuring battery consumption.
BatteryRunway
Result of battery runway estimation.
BatteryRunwayCalculator
Calculator for battery runway estimation.
BatteryService
Service interface for battery management and optimization.
BatteryServiceImpl
Implementation of BatteryService using method channel.
BatteryStats
Statistics about battery usage during location tracking.
BatteryThresholds
Battery level thresholds for optimization.
BenchmarkResult
Result of a battery benchmark session.
Config
Main configuration class for the background geolocation service.
ConfigPresets
Ready-to-use configuration presets for common tracking scenarios.
ConfigValidationError
A configuration validation error.
ConfigValidationResult
Result of a configuration validation.
ConfigValidationWarning
A configuration validation warning.
ConfigValidator
Validates Config objects for the Locus SDK.
ConnectivityChangeEvent
Coords
DeviceOptimizationService
Helpers for device-specific background execution behavior.
DiagnosticsSnapshot
ErrorContext
Context about the error for decision making.
ErrorRecoveryConfig
Configuration for error handling and recovery.
ErrorRecoveryManager
Manages error recovery for the Locus SDK.
EventMapper
Utility for mapping native platform events to typed Dart events.
FrequentLocation
A frequently visited location (cluster center).
Geofence
GeofenceEvent
GeofenceService
Service interface for geofencing operations.
GeofenceServiceImpl
Implementation of GeofenceService using method channel.
GeofenceWorkflow
GeofenceWorkflowEngine
GeofenceWorkflowEvent
GeofenceWorkflowState
GeofenceWorkflowStep
GeolocationEvent<T>
A generic geolocation event with typed payload.
GeolocationState
GeoPoint
A geographic coordinate point (vertex) for polygon geofences.
HeadlessEvent
HttpEvent
Location
LocationAnomaly
Represents a detected anomalous movement between two locations.
LocationAnomalyConfig
Configuration for detecting anomalous location jumps.
LocationAnomalyDetector
Detects anomalous location jumps in a Location stream.
LocationBounds
Geographic bounding box for spatial filtering.
LocationHistoryCalculator
Calculator for location history statistics.
LocationQuality
LocationQualityAnalyzer
LocationQualityConfig
LocationQuery
Query parameters for filtering location history.
LocationService
Service interface for location operations.
LocationServiceImpl
Implementation of LocationService using method channel.
LocationSummary
Summary of location history for a time period.
Locus
Main class for interacting with background geolocation services.
LocusAdaptive
Adaptive Tracking Logic.
LocusBattery
Battery and Power management.
LocusDebugOverlay
A debug overlay widget that displays real-time Locus information.
LocusDiagnostics
Diagnostics and Remote Commands.
LocusGeofencing
Geofencing operations.
LocusInterface
Contract for Locus implementations (method-channel or mock).
LocusLocation
Location operations.
LocusProfiles
Tracking Profiles management.
LocusSync
Sync operations.
LocusTrip
Trip lifecycle management.
LocusWorkflows
Geofence Workflows management.
LogEntry
LowBatteryConfig
Configuration for low battery optimization.
MockLocus
Mock implementation of Locus for unit testing.
NotificationConfig
Configuration for the foreground notification (Android).
PermissionAssistant
Guided permission workflow with optional UI delegate.
PermissionFlowDelegate
Delegate for permission workflow UI steps.
PermissionRationale
Configuration for permission rationale dialog.
PermissionService
Service for handling location and activity permissions.
PolygonGeofence
A geofence defined by a polygon (list of vertices).
PolygonGeofenceEvent
Event emitted when polygon geofence state changes.
PolygonGeofenceService
Service for managing polygon geofences.
PowerOptimizationSuggestion
Suggested optimization based on power state analysis.
PowerState
Current power state of the device.
PowerStateChangeEvent
Power state change event.
PrivacyService
Service interface for privacy zone operations.
PrivacyServiceImpl
Implementation of PrivacyService using method channel.
PrivacyZone
Defines a circular privacy zone where location data is protected.
PrivacyZoneEvent
Event emitted when a privacy zone changes.
PrivacyZoneResult
Result of applying privacy zone rules to a location.
PrivacyZoneService
Service for managing privacy zones and applying location obfuscation.
ProfileChangeEvent
Event emitted when a tracking profile changes.
ProfileSwitchError
Event emitted when a profile switch fails.
ProviderChangeEvent
QueueItem
RemoteCommand
RoutePoint
SignificantChangeConfig
Configuration for significant location change monitoring.
SignificantChangeEvent
Event emitted when a significant location change is detected.
SignificantChangeManager
Manager for significant location change monitoring.
SpeedTier
Configuration for a single speed tier.
SpeedTiers
Speed-based update interval tiers.
SpoofDetectionConfig
Configuration for spoof detection behavior.
SpoofDetectionEvent
Event emitted when spoofing is detected.
SpoofDetector
Analyzer for detecting spoofed locations.
SyncBodyContext
Context passed to headless sync body builder.
SyncDecision
Sync decision result from policy evaluation.
SyncPolicy
Network-aware sync policy configuration.
SyncService
Service interface for sync operations.
SyncServiceImpl
Implementation of SyncService using method channel.
TrackingProfileManager
TrackingProfileRule
TripConfig
TripEngine
TripEvent
TripService
Service interface for trip tracking operations.
TripServiceImpl
Implementation of TripService using method channel.
TripState
TripStore
TripSummary
WorkflowStateStore
Abstraction for workflow state persistence.

Enums

ActivityType
AuthorizationStatus
BatteryLevel
Battery level categories.
ChargingType
Type of charging connection.
DebugOverlayPosition
Position options for the debug overlay.
DesiredAccuracy
Desired location accuracy level.
EventType
Types of geolocation events.
GeofenceAction
GeofenceWorkflowStatus
LocationAccuracyAuthorization
LocationSortOrder
Sort order for location queries.
LocusErrorType
Classification of Locus errors.
LocusProfile
Tracking profile for adaptive behavior.
LogLevel
Log level for debugging.
NetworkType
Network connection type.
OptimizationLevel
Battery optimization level.
OptimizationSuggestionLevel
Optimization suggestion levels.
PersistMode
Persistence mode for location data.
PolygonGeofenceEventType
Types of polygon geofence events.
PowerStateChangeType
Types of power state changes.
PrivacyZoneAction
Action to take when a location is within a privacy zone.
PrivacyZoneEventType
Event types for privacy zone changes.
ProviderAvailability
RecoveryAction
Recovery action to take after an error.
RemoteCommandType
SpoofDetectionAction
Action to take when spoofing is detected.
SpoofFactor
Factors that can indicate location spoofing.
SpoofSensitivity
Sensitivity level for spoof detection.
SyncBehavior
Sync behavior options.
TrackingProfile
TrackingProfileRuleType
TripEventType

Extensions

MockActivityExtension on Activity
Extension to create mock Activity objects easily.
MockGeofenceExtension on Geofence
Extension to create mock Geofence objects easily.
MockLocationExtension on Location
Extension to create mock Location objects easily.
SpoofFactorDescription on SpoofFactor
Extension to get human-readable descriptions.

Constants

kDefaultActivityConfidence → const int
Default activity confidence.
kDefaultBatchSize → const int
Default sync batch size.
kDefaultCriticalBatteryThreshold → const int
Default critical battery threshold percentage.
kDefaultDistanceFilterMeters → const double
Default distance filter in meters.
kDefaultGeofenceRadiusMeters → const double
Default geofence radius in meters.
kDefaultHeartbeatIntervalSeconds → const int
Default heartbeat interval in seconds.
kDefaultLowBatteryThreshold → const int
Default low battery threshold percentage.
kDefaultMaxRecordsToPersist → const int
Default max records to persist.
kDefaultMinAccuracyMeters → const double
Default minimum accuracy in meters.
kDefaultMinSpoofFactors → const int
Default number of factors needed to detect spoofing.
kDefaultRouteDeviationThresholdMeters → const double
Default route deviation threshold in meters.
kDefaultSignificantChangeDisplacementMeters → const double
Default significant change displacement in meters.
kDefaultUpdateIntervalSeconds → const int
Default update interval in seconds.
kMaxAltitudeChangePerSecondMeters → const double
Maximum altitude change per second in meters (~360 km/h vertical). Used for spoof detection.
kMaxBatteryPercent → const int
Maximum battery percentage (100%).
kMaxConfidencePercent → const int
Maximum confidence percentage (100%).
kMaxDeadLetterQueueSize → const int
Maximum dead letter queue size.
kMaxLocationsInCache → const int
Maximum locations in memory cache.
kMaxLogStorageBytes → const int
Maximum log storage size in bytes.
kMaxPossibleSpeedKph → const double
Maximum possible speed in km/h (commercial jet speed). Used for spoof detection.
kMetersPerKilometer → const double
Meters per kilometer.
kMillisecondsPerSecond → const int
Milliseconds per second.
kMinActivityRecognitionIntervalMs → const int
Minimum activity recognition interval in milliseconds.
kMinBatteryPercent → const int
Minimum battery percentage (0%).
kRepeatedCoordinatesThreshold → const int
Threshold for repeated coordinates detection.
kSecondsPerDay → const int
Seconds per day.
kSecondsPerHour → const int
Seconds per hour.
kSecondsPerMinute → const int
Seconds per minute.

Typedefs

HeadlessEventCallback = Future<void> Function(HeadlessEvent event)
Callback type for headless background events.
JsonMap = Map<String, dynamic>
PolygonGeofencePersistCallback = Future<void> Function(List<PolygonGeofence> geofences)
Callback for polygon geofence persistence.
SyncBodyBuilder = Future<JsonMap> Function(List<Location> locations, JsonMap extras)
Callback type for building custom HTTP sync body.

Exceptions / Errors

ConfigValidationException
Exception thrown when configuration validation fails.
InvalidCoordsException
Exception thrown when coordinate data is invalid.
LocusError
Locus SDK error with classification and recovery hints.