### Basic Locus SDK Setup and Tracking in Flutter Source: https://pub.dev/packages/locus/index Initialize the Locus SDK with configuration, start background location tracking, and listen for location updates. This snippet demonstrates the fundamental steps to get location data from the SDK. ```dart import 'package:locus/locus.dart'; void main() async { // 1. Initialize await Locus.ready(ConfigPresets.balanced.copyWith( url: 'https://api.yourservice.com/locations', )); // 2. Start tracking await Locus.start(); // 3. Listen to updates Locus.location.stream.listen((location) { print('Location: ${location.coords.latitude}, ${location.coords.longitude}'); }); } ``` -------------------------------- ### Flutter Project Setup with Locus SDK Source: https://pub.dev/packages/locus/versions/1.2 This snippet demonstrates the basic steps to integrate the Locus SDK into a Flutter project. It includes adding the dependency, initializing the SDK with a configuration, starting location tracking, and setting up a listener for location updates. ```dart dependencies: locus: ^1.1.0 ``` ```dart import 'package:locus/locus.dart'; void main() async { // 1. Initialize await Locus.ready(Config.balanced( url: 'https://api.yourservice.com/locations', )); // 2. Start tracking await Locus.start(); // 3. Listen to updates Locus.onLocation((location) { print('Location: ${location.coords.latitude}, ${location.coords.longitude}'); }); } ``` -------------------------------- ### Run Example Application Source: https://pub.dev/packages/locus/versions/1.0 Instructions to run the example application provided with the Locus package. This involves navigating to the example directory and executing the Flutter run command. ```shell cd example flutter run ``` -------------------------------- ### Automated Setup and Verification CLI Source: https://pub.dev/packages/locus/versions/1.1 Utilize the Locus CLI tool for automating native permissions and project settings. The 'setup' command configures the project, while the 'doctor' command verifies the environment. ```dart dart run locus:setup ``` ```dart dart run locus:doctor ``` -------------------------------- ### Basic Locus SDK Initialization and Start Source: https://pub.dev/packages/locus/versions/1.1 Configure and start the Locus SDK with basic settings, including a synchronization URL and notification configuration. This enables background location tracking. ```dart await Locus.ready(Config.balanced( url: 'https://api.yourservice.com/locations', notification: NotificationConfig( title: 'Location Service', text: 'Tracking is active', ), )); await Locus.start(); ``` -------------------------------- ### Locus Setup Wizard Options Source: https://pub.dev/packages/locus/versions/1.0 This details the available options for the `dart run locus:setup` command, allowing for selective configuration of Android or iOS projects and the inclusion of activity recognition permissions. ```bash dart run locus:setup [options] Options: --android-only Only configure Android --ios-only Only configure iOS --with-activity Include activity recognition permissions -h, --help Show usage information ``` -------------------------------- ### Initialize and Configure Locus SDK in Flutter Source: https://pub.dev/packages/locus/versions/2.0.0/example This snippet shows the initial setup of the Locus SDK within a Flutter application. It includes requesting necessary location permissions, defining a comprehensive configuration object with various tracking and persistence settings, and initializing the SDK with this configuration. It also demonstrates setting up custom sync body builders and headers callbacks for data synchronization. ```dart import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:google_fonts/google_fonts.dart' hide Config; import 'package:locus/locus.dart'; void main() => runApp(const LocusExampleApp()); // ============================================================================= // App Entry Point // ============================================================================= class LocusExampleApp extends StatefulWidget { const LocusExampleApp({super.key}); @override State createState() => _LocusExampleAppState(); } class _LocusExampleAppState extends State { static const int _maxEventEntries = 250; final GlobalKey _scaffoldMessengerKey = GlobalKey(); // Stream subscriptions final List> _subscriptions = []; // State final List _events = []; final Map _eventCounts = {}; Location? _latestLocation; Activity? _lastActivity; ConnectivityChangeEvent? _lastConnectivity; GeolocationState? _lastState; List? _lastLog; PowerState? _powerState; BatteryStats? _batteryStats; BatteryRunway? _batteryRunway; AdaptiveSettings? _adaptiveSettings; AdaptiveTrackingConfig? _adaptiveTrackingConfig; PowerStateChangeEvent? _lastPowerEvent; List _storedLocations = []; LocationSummary? _locationSummary; List _syncQueue = []; DiagnosticsSnapshot? _diagnostics; List _polygonGeofences = []; List _privacyZones = []; GeofenceWorkflowEvent? _lastWorkflowEvent; LocationQuality? _lastQuality; LocationAnomaly? _lastAnomaly; StreamSubscription? _qualitySubscription; StreamSubscription? _anomalySubscription; // Toggles bool _isRunning = false; bool _isReady = false; bool _spoofDetectionEnabled = false; bool _significantChangesEnabled = false; bool _isSyncPaused = false; bool _automationEnabled = false; bool _qualityMonitoringEnabled = false; bool _anomalyMonitoringEnabled = false; bool _workflowRegistered = false; String? _benchmarkStatus; TrackingProfile? _currentProfile; SyncPolicy _syncPolicy = SyncPolicy.balanced; SyncDecision? _syncDecision; String? _lastQueueId; String _activeScenario = 'None'; Map _syncContext = const { 'shift_id': 'shift-001', 'driver_id': 'driver-42', 'route_id': 'route-7', }; @override void initState() { super.initState(); unawaited(_configure()); } @override void dispose() { unawaited(_qualitySubscription?.cancel()); unawaited(_anomalySubscription?.cancel()); for (final sub in _subscriptions) { unawaited(sub.cancel()); } super.dispose(); } // =========================================================================== // Configuration // =========================================================================== Future _configure() async { final isGranted = await Locus.requestPermission(); if (!isGranted) { _showSnackbar('Location permission required', isSuccess: false); return; } final config = Config( stationaryRadius: 25, motionTriggerDelay: 15000, activityRecognitionInterval: 10000, startOnBoot: true, stopOnTerminate: false, enableHeadless: true, autoSync: true, batchSync: true, maxBatchSize: 5, autoSyncThreshold: 1, queueMaxDays: 7, queueMaxRecords: 500, persistMode: PersistMode.location, maxDaysToPersist: 7, maxRecordsToPersist: 200, maxMonitoredGeofences: 20, url: 'https://example.com/locations', extras: _syncContext, adaptiveTracking: AdaptiveTrackingConfig.balanced, logLevel: LogLevel.info, notification: const NotificationConfig( title: 'Locus Example', text: 'Tracking location in background', ), ); await Locus.ready(config); await _configureProfiles(); _setupListeners(); await _refreshState(); await Locus.dataSync.setPolicy(_syncPolicy); await Locus.battery.setAdaptiveTracking(AdaptiveTrackingConfig.balanced); // Demo: Custom sync body builder await Locus.setSyncBodyBuilder((locations, extras) async { return { 'app': 'locus_example', 'timestamp': DateTime.now().toIso8601String(), 'locations': locations.map((l) => l.toMap()).toList(), ...extras, }; }); Locus.dataSync.setHeadersCallback(() async { return { 'X-Client': 'locus_example', 'X-Shift-Id': _syncContext['shift_id']?.toString() ?? 'unknown', }; }); } // Placeholder for _configureProfiles, _setupListeners, _refreshState, and _showSnackbar Future _configureProfiles() async { /* ... */ } void _setupListeners() { /* ... */ } Future _refreshState() async { /* ... */ } void _showSnackbar(String message, {bool isSuccess = true}) { /* ... */ } } ``` -------------------------------- ### Run Locus Setup Wizard via CLI Source: https://pub.dev/packages/locus/versions/1.0 This command executes the Locus setup wizard, which automatically configures Android and iOS projects with necessary permissions, plist entries, and background modes. Options include configuring only Android or iOS, and including activity recognition permissions. ```bash dart run locus:setup dart run locus:setup --android-only dart run locus:setup --ios-only dart run locus:setup --with-activity ``` -------------------------------- ### Configuring Locus with Presets Source: https://pub.dev/packages/locus/changelog Demonstrates the use of factory constructors `Config.fitness()` and `Config.passive()` for quick and convenient setup of the Locus SDK with predefined configurations. ```dart import 'package:locus/locus.dart'; void setupLocus() { // Using fitness preset final fitnessConfig = Config.fitness(); Locus.init(config: fitnessConfig); // Using passive preset final passiveConfig = Config.passive(); Locus.init(config: passiveConfig); } ``` -------------------------------- ### Build Tracking Controls with Start/Stop and Get Position Buttons Source: https://pub.dev/packages/locus/versions/2.0.0/example Creates a Card widget for controlling the tracking functionality. It features two main action buttons: 'Start'/'Stop' for toggling tracking and 'Get Position' to fetch the current location. ```dart Widget _buildTrackingControls() { return Card( child: Padding( padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const _SectionHeader( icon: Icons.play_circle_outline, title: 'Tracking', ), const SizedBox(height: 16), Row( children: [ Expanded( child: _ActionButton( onPressed: _toggleTracking, icon: _isRunning ? Icons.stop_rounded : Icons.play_arrow_rounded, label: _isRunning ? 'Stop' : 'Start', color: _isRunning ? Colors.red : Colors.green, filled: true, ), ), const SizedBox(width: 12), Expanded( child: _ActionButton( onPressed: _getPosition, icon: Icons.my_location_rounded, label: 'Get Position', ), ), ], ), ], ), ), ); } ``` -------------------------------- ### Managing Permission Sequences with PermissionAssistant Source: https://pub.dev/packages/locus/changelog Provides an example of using `PermissionAssistant` to manage complex sequences of permission requests, such as Location, Activity, and Notification permissions. It includes callbacks for UI updates during the process. ```dart import 'package:locus/locus.dart'; Future requestPermissions() async { final assistant = PermissionAssistant(); await assistant.requestSequence([ PermissionType.location, PermissionType.activity, PermissionType.notification, ], onStatusChanged: (type, status) { print('Permission $type status changed to $status'); // Update UI based on status }); } ``` -------------------------------- ### Install locus as Executable (Dart CLI) Source: https://pub.dev/packages/locus/install Installs the locus package globally as an executable using the Dart CLI. This command makes the package's command-line tools available system-wide. ```bash dart pub global activate locus ``` -------------------------------- ### Quick Configuration Presets Source: https://pub.dev/packages/locus/versions/1.2.0/changelog Provides factory constructors `Config.fitness()` and `Config.passive()` for rapid Locus SDK setup. These presets simplify the initial configuration process for common use cases. ```dart import 'package:locus/locus.dart'; // For fitness tracking scenarios final fitnessConfig = Config.fitness(); await Locus.initialize(config: fitnessConfig); // For passive background tracking scenarios final passiveConfig = Config.passive(); await Locus.initialize(config: passiveConfig); ``` -------------------------------- ### Mocking Locus Instance for Testing Source: https://pub.dev/packages/locus/versions/1.1 Demonstrates how to inject a mock Locus instance into your tests using `setUp` and `Locus.setMockInstance`. This allows for isolated testing of Locus functionalities without relying on the actual implementation. ```dart void main() { setUp(() { Locus.setMockInstance(MockLocus()); }); test('tracking starts correctly', () async { await Locus.start(); // Assert against your mock }); } ``` -------------------------------- ### Configure and Start Schedule Windows Source: https://pub.dev/packages/locus/versions/1.0 Configures tracking schedule windows and starts the schedule. Supports 24-hour format and midnight spanning. Requires Locus SDK and Config object. ```dart await Locus.ready(const Config( schedule: ['08:00-12:00', '13:00-18:00'], )); await Locus.startSchedule(); ``` -------------------------------- ### Initialize and Manage Locus Tracking Source: https://pub.dev/packages/locus/versions/1.2.0/example Demonstrates how to initialize the Locus package, start and stop location tracking, and refresh the tracking state. It also shows how to handle errors during these operations. ```dart Future _initLocus() async { await Locus.ready(); await _refreshState(); _activitySubscription = Locus.onActivity((event) { _recordEvent( 'activity', 'activity type=${event.type} confidence=${event.confidence}', updateState: () => _lastActivity = event, ); }, onError: _onError); _httpSubscription = Locus.onHttp((event) { _recordEvent( 'http', 'http status=${event.status} ok=${event.ok}', updateState: () => _lastHttp = event, ); }, onError: _onError); _notificationActionSubscription = Locus.onNotificationAction((action) { _recordEvent( 'notification', 'notification action=$action', updateState: () => _lastNotificationAction = action, ); }, onError: _onError); } ``` -------------------------------- ### Install Locus SDK Source: https://pub.dev/packages/locus/versions/1.1 Add the Locus SDK dependency to your Flutter project's pubspec.yaml file. This is the initial step to include the library in your project. ```yaml dependencies: locus: ^1.1.0 ``` -------------------------------- ### Initialize Locus SDK and Add Geofence with Specific Imports Source: https://pub.dev/packages/locus/index A Flutter example demonstrating how to initialize the Locus SDK and add a geofence using specific imports to potentially improve tree shaking. This approach imports only the necessary components. ```dart import 'package:locus/locus.dart' show Locus, Config, Geofence, GeoPoint; Future initTracking() async { await Locus.ready(const Config()); await Locus.start(); await Locus.geofencing.add(Geofence( identifier: 'office', latitude: 37.7749, longitude: -122.4194, radius: 100, )); } ``` -------------------------------- ### Trip Management and Logging Source: https://pub.dev/packages/locus/versions/1.1.0/example Illustrates how to start and stop trips with specific configurations, and how to manage application logs, including loading and emailing them. Also shows how to clear recorded events. ```dart Future _startTrip() async { await Locus.startTrip(const TripConfig( startOnMoving: true, updateIntervalSeconds: 30, route: [ RoutePoint(latitude: 37.4219983, longitude: -122.084), RoutePoint(latitude: 37.4279613, longitude: -122.0857497), ], routeDeviationThresholdMeters: 150, )); _recordEvent('trip', 'trip start requested'); } Future _stopTrip() async { final summary = Locus.stopTrip(); setState(() { _lastTripSummary = summary; }); _recordEvent('trip', 'trip stop requested'); } Future _loadLog() async { final log = await Locus.getLog(); setState(() { _lastLog = log; }); } Future _emailLog() async { await Locus.emailLog('logs@example.com'); _showSnackbar('Requested log email'); } void _clearEvents() { setState(() { _events.clear(); _eventCounts.clear(); }); } ``` -------------------------------- ### Setup Schedule Listener with Locus SDK Source: https://pub.dev/packages/locus/versions/1.1.0/example Sets up a listener for scheduled location updates from the Locus SDK. It records schedule events. Includes error handling. ```dart _scheduleSubscription = Locus.onSchedule((location) { _recordEvent('schedule', _formatLocationEvent(location, 'schedule')); }, onError: _onError); ``` -------------------------------- ### Build Action Button Widget (Dart) Source: https://pub.dev/packages/locus/versions/2.0.0/example Provides an `_ActionButton` widget that can be rendered as either a filled or outlined button. It includes an icon and label, with customizable color and an `onPressed` callback for handling user interaction. ```dart class _ActionButton extends StatelessWidget { const _ActionButton({ required this.onPressed, required this.icon, required this.label, this.color, this.filled = false, }); final VoidCallback onPressed; final IconData icon; final String label; final Color? color; final bool filled; @override Widget build(BuildContext context) { final effectiveColor = color ?? Theme.of(context).colorScheme.primary; if (filled) { return FilledButton.icon( onPressed: onPressed, icon: Icon(icon, size: 18), label: Text(label), style: FilledButton.styleFrom( backgroundColor: effectiveColor, padding: const EdgeInsets.symmetric(vertical: 12), ), ); } return OutlinedButton.icon( onPressed: onPressed, ``` -------------------------------- ### Build AppBar with Logo, Title, and Refresh Button Source: https://pub.dev/packages/locus/versions/2.0.0/example Constructs the AppBar for the application, including the Locus logo, the application title 'Locus', and an IconButton for refreshing the state. It also defines the TabBar for navigation. ```dart AppBar( leading: SvgPicture.asset( 'assets/locus_logo.svg', width: 32, height: 32, ), title: const Text('Locus'), actions: [ IconButton( onPressed: _refreshState, icon: const Icon(Icons.refresh_rounded), tooltip: 'Refresh', ), ], bottom: const TabBar( tabs: [ Tab(icon: Icon(Icons.dashboard_rounded), text: 'Dashboard'), Tab(icon: Icon(Icons.list_alt_rounded), text: 'Events'), Tab(icon: Icon(Icons.storage_rounded), text: 'Storage'), Tab(icon: Icon(Icons.settings_rounded), text: 'Settings'), ], ), ) ``` -------------------------------- ### Register and Clear Geofencing Workflows (Dart) Source: https://pub.dev/packages/locus/versions/2.0.0/example Demonstrates how to register a geofencing workflow with specific geofence configurations and how to subsequently clear all registered workflows. This involves defining geofence actions, identifiers, and cooldown periods. ```dart void _registerDeliveryWorkflow() { final workflow = Workflow( id: 'dropoff', geofenceIdentifier: 'delivery_dropoff', action: GeofenceAction.enter, cooldownSeconds: 30, ); Locus.geofencing.registerWorkflows([workflow]); setState(() => _workflowRegistered = true); _showSnackbar('Workflow registered'); _recordEvent('workflow', 'Registered delivery workflow'); } void _stopWorkflows() { Locus.geofencing.stopWorkflows(); Locus.geofencing.clearWorkflows(); setState(() => _workflowRegistered = false); _showSnackbar('Workflows cleared'); _recordEvent('workflow', 'Workflows cleared'); } ``` -------------------------------- ### Build Dashboard Layout with List of Widgets Source: https://pub.dev/packages/locus/versions/2.0.0/example Builds the main content area for the Dashboard tab using a ListView. It arranges various status cards, controls, and informational widgets vertically with spacing. ```dart Widget _buildDashboard() { return ListView( padding: const EdgeInsets.all(16), children: [ _buildStatusCard(), const SizedBox(height: 16), _buildTrackingControls(), const SizedBox(height: 16), _buildProfileSelector(), const SizedBox(height: 16), _buildQuickActions(), const SizedBox(height: 16), _buildGeofencingTools(), const SizedBox(height: 16), _buildUseCases(), const SizedBox(height: 16), _buildEventStats(), ], ); } ``` -------------------------------- ### Setup Enabled Change Listener with Locus SDK Source: https://pub.dev/packages/locus/versions/1.1.0/example Sets up a listener for changes in the Locus SDK's enabled status. It records whether the SDK is enabled. Includes error handling. ```dart _enabledSubscription = Locus.onEnabledChange((enabled) { _recordEvent( 'enabledchange', ``` -------------------------------- ### Build Geofencing Tools Widget in Flutter Source: https://pub.dev/packages/locus/versions/2.0.0/example Creates a geofencing tools widget using Flutter's Card and Column. It displays a section header for geofencing and is intended to show workflow status. ```dart Widget _buildGeofencingTools() { final workflowStatus = _lastWorkflowEvent?.status.name ?? 'idle'; return Card( child: Padding( padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const _SectionHeader( icon: Icons.map_outlined, title: 'Geofencing', ), ``` -------------------------------- ### Configure Adaptive Tracking (Dart) Source: https://pub.dev/packages/locus/versions/2.0.0/example Sets the adaptive tracking configuration for battery optimization. This function takes a configuration object and a label to describe the setting, updating the SDK's behavior accordingly. ```dart Future _setAdaptiveTracking( AdaptiveTrackingConfig config, String label, ) async { await Locus.battery.setAdaptiveTracking(config); setState(() => _adaptiveTrackingConfig = config); _showSnackbar('Adaptive: $label'); _recordEvent('battery', 'Adaptive tracking: $label'); } ``` -------------------------------- ### Storage Management UI - Flutter Source: https://pub.dev/packages/locus/versions/2.0.0/example Builds the UI for the storage tab, allowing users to load and clear stored locations. It uses Card widgets for a structured layout and ActionButton widgets for interactive elements. ```dart Widget _buildStorage() { return ListView( padding: const EdgeInsets.all(16), children: [ Card( child: Padding( padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _SectionHeader( icon: Icons.storage_rounded, title: 'Stored Locations', trailing: Container( padding: const EdgeInsets.symmetric( horizontal: 10, vertical: 4, ), decoration: BoxDecoration( color: const Color(0xFFF0F0F0), borderRadius: BorderRadius.circular(20), ), child: Text( '${_storedLocations.length}', style: const TextStyle( fontSize: 12, fontWeight: FontWeight.w600, ), ), ), ), const SizedBox(height: 16), Row( children: [ Expanded( child: _ActionButton( onPressed: _loadLocations, icon: Icons.download_rounded, label: 'Load', filled: true, ), ), const SizedBox(width: 12), Expanded( child: _ActionButton( onPressed: _clearLocations, icon: Icons.delete_outline_rounded, label: 'Clear', ), ), ], ), ], ), ), ), if (_storedLocations.isNotEmpty) ...[ const SizedBox(height: 16), Card( child: ListView.separated( shrinkWrap: true, physics: const NeverScrollableScrollPhysics(), ``` -------------------------------- ### Setup Geofence Listener with Locus SDK Source: https://pub.dev/packages/locus/versions/1.1.0/example Sets up a listener for geofence events from the Locus SDK. It records geofence entry/exit events and updates the last geofence event. Includes error handling. ```dart _geofenceSubscription = Locus.onGeofence((event) { _recordEvent( 'geofence', 'geofence ${event.geofence.identifier} ${event.action.name}', updateState: () => _lastGeofence = event, ); }, onError: _onError); ``` -------------------------------- ### Control Locus SDK Trip Recording Source: https://pub.dev/packages/locus/versions/2.0.0/example Starts and stops trip recording using the Locus SDK. It provides feedback on trip start and displays the distance upon stopping. This functionality relies on Locus.trips.start() with TripConfig and Locus.trips.stop(). ```dart Future _startTrip() async { await Locus.trips.start(const TripConfig(startOnMoving: true)); _showSnackbar('Trip started'); _recordEvent('trip', 'Trip started'); } Future _stopTrip() async { final summary = await Locus.trips.stop(); // setState(() => _lastTripSummary = summary); if (summary != null) { _showSnackbar('Trip: ${summary.distanceMeters.toStringAsFixed(0)}m'); } else { _showSnackbar('Trip stopped'); } _recordEvent('trip', 'Trip stopped'); } ``` -------------------------------- ### Location and Geofencing Operations Source: https://pub.dev/packages/locus/versions/1.1.0/example Provides examples for getting the current location, managing geofences (adding and removing), and retrieving stored locations. It also includes toggling the scheduler. ```dart Future _getCurrentPosition() async { try { final location = await Locus.getCurrentPosition(); _showSnackbar( 'Position: ${location.coords.latitude.toStringAsFixed(5)}, ${location.coords.longitude.toStringAsFixed(5)}', ); _recordEvent( 'currentposition', _formatLocationEvent(location, 'getCurrentPosition'), updateState: () => _latestLocation = location, ); } catch (e) { _onError(e); } } Future _toggleSchedule() async { if (_scheduleEnabled) { await Locus.stopSchedule(); } else { await Locus.startSchedule(); } setState(() { _scheduleEnabled = !_scheduleEnabled; }); } Future _loadStoredLocations() async { final locations = await Locus.getLocations(limit: 50); setState(() { _storedLocations = locations; }); } Future _clearStoredLocations() async { await Locus.destroyLocations(); setState(() { _storedLocations = []; }); } Future _addDemoGeofence() async { await Locus.addGeofence(const Geofence( identifier: 'demo_geofence', radius: 100, latitude: 37.4219983, longitude: -122.084, notifyOnEntry: true, notifyOnExit: true, notifyOnDwell: true, loiteringDelay: 300000, extras: {'source': 'example'}, )); _showSnackbar('Geofence added'); } Future _removeAllGeofences() async { await Locus.removeGeofences(); _showSnackbar('Geofences cleared'); } ``` -------------------------------- ### Toggle Location Anomaly Monitoring (Dart) Source: https://pub.dev/packages/locus/versions/2.0.0/example Starts or stops monitoring for location anomalies, such as excessive speed. When enabled, it listens for anomaly events and logs them. Configurable with maximum speed thresholds. ```dart Future _toggleAnomalyMonitoring() async { if (_anomalyMonitoringEnabled) { await _anomalySubscription?.cancel(); setState(() { _anomalyMonitoringEnabled = false; _lastAnomaly = null; }); _showSnackbar('Anomaly monitoring stopped'); return; } _anomalySubscription = Locus.locationAnomalies( config: const LocationAnomalyConfig(maxSpeedKph: 180), ).listen((anomaly) { setState(() => _lastAnomaly = anomaly); _recordEvent( 'anomaly', 'Anomaly: ${anomaly.speedKph.toStringAsFixed(0)} kph', ); }); setState(() => _anomalyMonitoringEnabled = true); _showSnackbar('Anomaly monitoring started'); } ``` -------------------------------- ### Add Locus Dependency to pubspec.yaml Source: https://pub.dev/packages/locus/versions/1.0 This snippet shows how to add the Locus package as a dependency in your Flutter project's `pubspec.yaml` file. After adding, run `flutter pub get` to install the package. ```yaml dependencies: locus: ^1.0.0 ``` -------------------------------- ### Activate Delivery Operations - Dart Source: https://pub.dev/packages/locus/versions/2.0.0/example Initiates the 'Delivery Ops' scenario by starting the Locus SDK if not already running, setting the active scenario, and displaying a confirmation snackbar. It also records the activation event. ```dart Future _activateDeliveryOps() async { if (!_ensureReady()) return; final routes = [ RoutePoint(latitude: 37.4215, longitude: -122.0834), ]; // Assuming Route.new is a constructor or factory method final route = Route.new( points: routes, ); if (!_isRunning) { await Locus.start(); } setState(() => _activeScenario = 'Delivery Ops'); _showSnackbar('Delivery ops ready'); _recordEvent('scenario', 'Delivery ops activated'); } ``` -------------------------------- ### Activate Delivery Operations (Dart) Source: https://pub.dev/packages/locus/versions/2.0.0/example Initiates a sequence of operations for delivery tasks, including applying sync context and policies, setting adaptive tracking, registering workflows, configuring profiles, and starting a trip. ```dart Future _activateDeliveryOps() async { if (!_ensureReady()) return; await _applySyncContext({ 'shift_id': 'shift-204', 'driver_id': 'driver-17', 'route_id': 'route-5', 'tenant': 'west-coast', }); await _applySyncPolicy(SyncPolicy.balanced, 'Balanced'); await _setAdaptiveTracking(AdaptiveTrackingConfig.balanced, 'Balanced'); await _registerDeliveryWorkflow(); await _configureProfiles(enableAutomation: true); if (Locus.trips.getState() == null) { await Locus.trips.start( const TripConfig( tripId: 'delivery-204', startOnMoving: true, destination: RoutePoint( latitude: 37.4187, longitude: -122.0816, ), waypoints: [ ``` -------------------------------- ### Toggle Location Quality Monitoring (Dart) Source: https://pub.dev/packages/locus/versions/2.0.0/example Starts or stops monitoring the quality of location data. When enabled, it listens for location quality updates and displays them. Includes configuration for maximum accuracy and window size. ```dart Future _toggleQualityMonitoring() async { if (_qualityMonitoringEnabled) { await _qualitySubscription?.cancel(); setState(() { _qualityMonitoringEnabled = false; _lastQuality = null; }); _showSnackbar('Quality monitoring stopped'); return; } _qualitySubscription = Locus.locationQuality( config: const LocationQualityConfig(maxAccuracyMeters: 80, windowSize: 5), ).listen((quality) { setState(() => _lastQuality = quality); _recordEvent( 'quality', 'Quality: ${(quality.overallScore * 100).toStringAsFixed(0)}%', ); }); setState(() => _qualityMonitoringEnabled = true); _showSnackbar('Quality monitoring started'); } ``` -------------------------------- ### Load Location Summary (Dart) Source: https://pub.dev/packages/locus/versions/2.0.0/example Retrieves a summary of location data within the last 12 hours, with a limit of 250 points. This function is used to get a concise overview of recent location activity. ```dart Future _loadLocationSummary() async { final summary = await Locus.location.getSummary( query: LocationQuery.lastHours(12, limit: 250), ); setState(() => _locationSummary = summary); _showSnackbar('Summary: ${summary.locationCount} points'); } ``` -------------------------------- ### Control Locus SDK Battery Benchmark Source: https://pub.dev/packages/locus/versions/2.0.0/example Starts and stops a battery benchmark test using the Locus SDK. It updates the UI to reflect the benchmark status and provides user feedback. This involves Locus.startBatteryBenchmark() and Locus.stopBatteryBenchmark(). ```dart Future _toggleBenchmark() async { if (_benchmarkStatus == null) { await Locus.startBatteryBenchmark(); setState(() => _benchmarkStatus = 'Running'); _showSnackbar('Benchmark started'); } else { await Locus.stopBatteryBenchmark(); setState(() => _benchmarkStatus = null); _showSnackbar('Benchmark stopped'); } } ``` -------------------------------- ### Locus SDK Project Tooling Commands Source: https://pub.dev/packages/locus/index Utilize the Locus CLI for project automation and diagnostics. Commands include setting up native permissions, running environment checks, and assisting with migration from older versions. ```bash # Automate native permission setup dart run locus:setup # Run environment diagnostics dart run locus:doctor # Migration helper (v1.x to v2.0) dart run locus:migrate --dry-run ``` -------------------------------- ### Start Trip with Locus SDK Source: https://pub.dev/packages/locus/example Initiates a new trip recording session using the Locus SDK. The trip is configured to start automatically when the device detects movement. ```dart Future _startTrip() async { await Locus.trips.start(const TripConfig(startOnMoving: true)); _showSnackbar('Trip started'); _recordEvent('trip', 'Trip started'); } ``` -------------------------------- ### Build Settings UI for Battery and Power Source: https://pub.dev/packages/locus/versions/2.0.0/example Renders the settings tab UI, displaying battery level, GPS on time, charging status, and last power event. Includes buttons to refresh battery status and toggle benchmarking. Dependencies include `ListView`, `Card`, `Padding`, `Column`, `_SectionHeader`, `_InfoRow`, and `_ActionButton` widgets. ```dart Widget _buildSettings() { return ListView( padding: const EdgeInsets.all(16), children: [ Card( child: Padding( padding: const EdgeInsets.all(20), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _SectionHeader( icon: Icons.battery_charging_full_rounded, title: 'Battery', trailing: _powerState != null ? Text( '${_powerState!.batteryLevel}%', style: const TextStyle(fontWeight: FontWeight.w600), ) : null, ), const SizedBox(height: 16), if (_batteryStats != null) ...[ _InfoRow( icon: Icons.gps_fixed, label: 'GPS On Time', value: '${(_batteryStats!.gpsOnTimePercent * 100).toStringAsFixed(1)}%', ), const SizedBox(height: 8), ], if (_powerState != null) _InfoRow( icon: Icons.power, label: 'Charging', value: _powerState!.isCharging ? 'Yes' : 'No', ), if (_lastPowerEvent != null) _InfoRow( icon: Icons.power_settings_new, label: 'Last Power Change', value: _lastPowerEvent!.changeType.name, ), Row( children: [ Expanded( child: _ActionButton( onPressed: _refreshBattery, icon: Icons.refresh_rounded, label: 'Refresh', filled: true, ), ), const SizedBox(width: 12), Expanded( child: _ActionButton( onPressed: _toggleBenchmark, icon: _benchmarkStatus != null ? Icons.stop_rounded : Icons.speed_rounded, ), ), ], ), ], ), ), ), ], ); } ``` -------------------------------- ### Configuring Native Sync Envelope Source: https://pub.dev/packages/locus/changelog Demonstrates how to configure the native sync envelope using the `extras` field and `httpRootProperty`. This enables custom JSON structures for HTTP sync bodies on both Android and iOS without requiring Dart callbacks. ```dart import 'package:locus/locus.dart'; void setupNativeSyncEnvelope() { final config = Config( // ... other config options ... extras: { 'customField': 'value', }, httpRootProperty: 'syncData', ); Locus.init(config: config); } ``` -------------------------------- ### Initialize and Manage Locus Service Source: https://pub.dev/packages/locus/versions/1.1.0/example Demonstrates how to initialize the Locus service, start/stop tracking, and refresh its state. It includes setting up listeners for HTTP events and notification actions. ```dart void initState() { super.initState(); _initLocus(); } Future _initLocus() async { await Locus.ready(); await _refreshState(); _activitySubscription = Locus.onActivity((event) { _recordEvent( 'activity', 'activity type=${event.type} confidence=${event.confidence}', updateState: () => _lastActivity = event, ); }, onError: _onError); _httpSubscription = Locus.onHttp((event) { _recordEvent( 'http', 'http status=${event.status} ok=${event.ok}', updateState: () => _lastHttp = event, ); }, onError: _onError); _notificationActionSubscription = Locus.onNotificationAction((action) { _recordEvent( 'notification', 'notification action=$action', updateState: () => _lastNotificationAction = action, ); }, onError: _onError); } Future _refreshState() async { final state = await Locus.getState(); setState(() { _lastState = state; _isRunning = state.enabled; _scheduleEnabled = state.schedulerEnabled ?? _scheduleEnabled; }); } Future _startOrStopTracking() async { if (!_isReady) { _showSnackbar('Call ready() first.'); return; } if (_isRunning) { await Locus.stop(); } else { await Locus.start(); } await _refreshState(); } ``` -------------------------------- ### Manage Locus SDK Geofences Source: https://pub.dev/packages/locus/versions/2.0.0/example Demonstrates adding a geofence and clearing all existing geofences using the Locus SDK. It provides feedback on the number of geofences present and logs the actions. This involves Locus.geofencing.add(), Locus.geofencing.getAll(), and Locus.geofencing.removeAll(). ```dart Future _addGeofence() async { await Locus.geofencing.add( const Geofence( identifier: 'demo_geofence', radius: 100, latitude: 37.4219983, longitude: -122.084, notifyOnEntry: true, notifyOnExit: true, ), ); final count = (await Locus.geofencing.getAll()).length; _showSnackbar('Geofence added ($count total)'); _recordEvent('geofence', 'Added demo_geofence'); } Future _clearGeofences() async { final count = (await Locus.geofencing.getAll()).length; await Locus.geofencing.removeAll(); _showSnackbar('Cleared $count geofence(s)'); _recordEvent('geofence', 'Cleared all'); } ``` -------------------------------- ### Start or Stop Location Tracking with Locus Source: https://pub.dev/packages/locus/versions/1.0.0/example Toggles the Locus tracking service between started and stopped states. It first checks if the service is ready and then calls `Locus.start()` or `Locus.stop()`. After the action, it refreshes the current state. ```dart Future _startOrStopTracking() async { if (!_isReady) { _showSnackbar('Call ready() first.'); return; } if (_isRunning) { await Locus.stop(); } else { await Locus.start(); } await _refreshState(); } ``` -------------------------------- ### Initial Release: Adaptive Tracking and Sync Policies (Dart) Source: https://pub.dev/packages/locus/changelog Describes the adaptive tracking and synchronization policies introduced in the initial Locus SDK release. These policies allow the SDK to adjust its behavior based on device status and user context for optimized performance and battery life. ```dart import 'package:locus/locus.dart'; void setupAdaptivePolicies() { final config = Config( // ... other config options ... trackingPolicy: TrackingPolicy.adaptive, syncPolicy: SyncPolicy.adaptive, ); Locus.init(config: config); } ``` -------------------------------- ### Initial Release: Adaptive Tracking and Sync Policies Source: https://pub.dev/packages/locus/versions/1.2.0/changelog Details the adaptive tracking and sync policies introduced in the initial release. These policies allow the SDK to adjust its behavior based on factors like battery level or network conditions. ```dart import 'package:locus/locus.dart'; Future configureAdaptivePolicies() async { final config = Config( // Example: Adjust tracking frequency based on battery level adaptiveTrackingPolicy: ( lowBatteryThreshold: 0.2, lowBatteryInterval: Duration(minutes: 30), normalInterval: Duration(minutes: 5), ), // Example: Adjust sync frequency based on network type adaptiveSyncPolicy: ( wifiInterval: Duration(minutes: 5), cellularInterval: Duration(minutes: 15), noConnectionInterval: Duration(hours: 1), ), // ... other configurations ... ); await Locus.initialize(config: config); print('Adaptive tracking and sync policies configured.'); } ``` -------------------------------- ### Configure and Start Location Tracking with Locus Source: https://pub.dev/packages/locus/versions/1.0 Sets up the Locus tracking configuration with various parameters like accuracy, distance filter, and notification settings. After configuration, it starts the tracking service if it's not already enabled. ```dart final state = await Locus.ready(const Config( desiredAccuracy: DesiredAccuracy.high, distanceFilter: 25, heartbeatInterval: 60, activityRecognitionInterval: 10000, stopTimeout: 5, stationaryRadius: 25, motionTriggerDelay: 15000, enableHeadless: true, startOnBoot: true, stopOnTerminate: false, autoSync: true, disableAutoSyncOnCellular: true, maxRetry: 3, retryDelay: 5000, retryDelayMultiplier: 2.0, maxRetryDelay: 60000, logLevel: LogLevel.info, logMaxDays: 7, url: 'https://example.com/locations', notification: NotificationConfig( title: 'Tracking enabled', text: 'Locus is tracking your location', actions: ['PAUSE', 'STOP'], ), )); if (!state.enabled) { await Locus.start(); } ``` -------------------------------- ### Initialize and Configure Locus SDK in Flutter Source: https://pub.dev/packages/locus/example Demonstrates the initial setup and configuration of the Locus SDK in a Flutter application. It requests location permissions, defines a comprehensive configuration object, and initializes the SDK. Dependencies include 'locus' and potentially other Flutter packages for UI and utilities. ```dart import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:google_fonts/google_fonts.dart' hide Config; import 'package:locus/locus.dart'; void main() => runApp(const LocusExampleApp()); // ... (rest of the App class) Future _configure() async { final isGranted = await Locus.requestPermission(); if (!isGranted) { _showSnackbar('Location permission required', isSuccess: false); return; } final config = Config( stationaryRadius: 25, motionTriggerDelay: 15000, activityRecognitionInterval: 10000, startOnBoot: true, stopOnTerminate: false, enableHeadless: true, autoSync: true, batchSync: true, maxBatchSize: 5, autoSyncThreshold: 1, queueMaxDays: 7, queueMaxRecords: 500, persistMode: PersistMode.location, maxDaysToPersist: 7, maxRecordsToPersist: 200, maxMonitoredGeofences: 20, url: 'https://example.com/locations', extras: _syncContext, adaptiveTracking: AdaptiveTrackingConfig.balanced, logLevel: LogLevel.info, notification: const NotificationConfig( title: 'Locus Example', text: 'Tracking location in background', ), ); await Locus.ready(config); await _configureProfiles(); _setupListeners(); await _refreshState(); await Locus.dataSync.setPolicy(_syncPolicy); await Locus.battery.setAdaptiveTracking(AdaptiveTrackingConfig.balanced); // Demo: Custom sync body builder await Locus.setSyncBodyBuilder((locations, extras) async { return { 'app': 'locus_example', 'timestamp': DateTime.now().toIso8601String(), 'locations': locations.map((l) => l.toMap()).toList(), ...extras, }; }); Locus.dataSync.setHeadersCallback(() async { return { 'X-Client': 'locus_example', }; }); } // ... (rest of the dispose and other methods) ``` -------------------------------- ### Mocking Locus Instance for Testing Source: https://pub.dev/packages/locus/versions/1.2.0/changelog Demonstrates how to use `setMockInstance()` to mock the Locus SDK for unit testing. This allows developers to isolate and test components that depend on Locus without requiring a live SDK instance. ```dart import 'package:locus/locus.dart'; // ... in your test setup ... // Mock the Locus instance Locus.setMockInstance(MockLocus()); // Now you can use Locus in your tests, and it will use the mock // For example: // await Locus.someMethod(); // Define your mock class (example) class MockLocus implements Locus { // Implement Locus methods with mock behavior @override Future initialize() async { print('Mock initialize called'); } // ... other methods ... } ``` -------------------------------- ### Get Current State Source: https://pub.dev/packages/locus/versions/1.0 Retrieves the current state of the Locus service. Uses the Locus SDK. ```dart final state = await Locus.getState(); ``` -------------------------------- ### Locus SDK Project Tooling Commands Source: https://pub.dev/packages/locus/versions/1.2 This snippet shows command-line interface (CLI) commands provided by the Locus SDK for Flutter projects. These commands help automate native permission setup and run environment diagnostics to ensure the SDK is configured correctly. ```bash # Automate native permission setup dart run locus:setup # Run environment diagnostics dart run locus:doctor ``` -------------------------------- ### Manage Background Tasks Source: https://pub.dev/packages/locus/versions/1.0 Starts and stops background tasks, allowing for short periods of background work. Uses the Locus SDK. ```dart final taskId = await Locus.startBackgroundTask(); // Do short background work here. await Locus.stopBackgroundTask(taskId); ```