flutter_get_background_loc 0.11.1
flutter_get_background_loc: ^0.11.1 copied to clipboard
Accurate background location for Flutter with GNSS quality metrics, fake-GPS detection, adaptive Kalman filtering and offline-safe uploads.
example/lib/main.dart
import 'dart:async';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_get_background_loc/flutter_get_background_loc.dart';
// Keeps the background entry point compiled into release builds.
export 'package:flutter_get_background_loc/flutter_get_background_loc.dart'
show flutterGetBackgroundLocBackgroundMain;
void main() => runApp(const ExampleApp());
/// Example app: permissions, start / stop, presets, live streams, health, GNSS warm-up and the
/// optional indoor / anchor / low-power options. See the package README for every option.
class ExampleApp extends StatelessWidget {
/// Creates the example app.
const ExampleApp({super.key});
@override
Widget build(BuildContext context) => MaterialApp(
title: 'Background Location Example',
theme: ThemeData(colorSchemeSeed: Colors.teal, useMaterial3: true),
home: const ExamplePage(),
);
}
/// The single screen of the example.
class ExamplePage extends StatefulWidget {
/// Creates the page.
const ExamplePage({super.key});
@override
State<ExamplePage> createState() => _ExamplePageState();
}
class _ExamplePageState extends State<ExamplePage> {
final _loc = FlutterGetBackgroundLoc();
final _subs = <StreamSubscription<dynamic>>[];
final _events = <String>[];
Timer? _healthTimer;
LocationFix? _fix;
MotionUpdate? _motion;
Heartbeat? _heartbeat;
HealthStatus? _health;
GnssWarmUpResult? _warmUp;
TrackingPreset _preset = TrackingPreset.balanced;
bool _robustIndoor = true; // opt-in indoor score / state
bool _anchorTrailExit = true; // leave a parked anchor on an outward trail
bool _stillProbe = true; // Android: high-accuracy probe after low-power silence
bool _running = false;
bool _warming = false;
String _message = '';
@override
void initState() {
super.initState();
_subs
..add(_loc.positionStream.listen((f) => setState(() => _fix = f)))
..add(_loc.motionStream.listen((m) => setState(() => _motion = m)))
..add(_loc.heartbeatStream.listen((h) => setState(() => _heartbeat = h)))
..add(_loc.statusStream.listen(_onStatus));
_healthTimer = Timer.periodic(const Duration(seconds: 10), (_) => _refresh());
unawaited(_refresh());
}
@override
void dispose() {
for (final s in _subs) {
unawaited(s.cancel());
}
_healthTimer?.cancel();
super.dispose();
}
void _onStatus(Map<dynamic, dynamic> e) {
// Includes `priorityChanged`, `stillProbe`, `watchdogRestart`, `presetChanged`, ...
final t = TimeOfDay.now().format(context);
final line = '$t ${e['status'] ?? e['type'] ?? ''} ${e['message'] ?? e['value'] ?? ''}'
.trim();
setState(() {
_events.insert(0, line);
if (_events.length > 8) _events.removeLast();
});
}
/// The tracking configuration: a preset plus the options shown on screen.
LocationConfig _config() => LocationConfig.forPreset(
_preset,
base: LocationConfig(
notification: const NotificationConfig(
title: 'Tracking',
text: 'Location tracking is active',
),
heartbeat: const HeartbeatConfig(intervalMs: 60000),
indoor: IndoorConfig(
anchorTrailExitEnabled: _anchorTrailExit,
robust: RobustIndoorConfig(enabled: _robustIndoor),
),
motion: MotionConfig(
stillProbeIntervalMs: _stillProbe ? 120000 : 0,
stillProbeDurationMs: 20000,
),
),
);
Future<void> _refresh() async {
final running = await _loc.isRunning();
final health = await _loc.healthCheck();
if (mounted) {
setState(() {
_running = running;
_health = health;
});
}
}
Future<void> _start() async {
// Shows the rationale and permission dialogs (location, "all the time", notifications ...).
final flow = await LocationPermissionFlow.run(context);
if (!mounted) return;
if (!flow.permission.isGranted) {
setState(() => _message = 'Location permission is required to track.');
return;
}
final ok = await _loc.startService(config: _config());
setState(() => _message = ok ? '' : 'The service did not start.');
await _refresh();
}
Future<void> _stop() async {
await _loc.stopService();
await _refresh();
}
Future<void> _setPreset(TrackingPreset p) async {
setState(() => _preset = p);
if (_running) await _loc.setPreset(p); // applied in place, no restart
}
/// Options change while running are applied with updateConfig (no restart).
Future<void> _applyOptions() async {
if (_running) await _loc.updateConfig(_config());
}
/// Optional: prime the GNSS receiver while online and outdoors, before going offline.
Future<void> _warmUpGnss() async {
setState(() => _warming = true);
final result = await _loc.warmUpGnss(timeout: const Duration(seconds: 60), targetAccuracyM: 25);
if (!mounted) return;
setState(() {
_warmUp = result;
_warming = false;
});
await _refresh();
}
@override
Widget build(BuildContext context) {
final f = _fix;
final h = _health;
final m = _motion;
final hb = _heartbeat;
final warmUp = _warmUp;
final age = h?.gnssDataAge;
return Scaffold(
appBar: AppBar(title: const Text('Background Location Example')),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
Wrap(
spacing: 8,
runSpacing: 8,
children: [
if (!_running)
FilledButton.icon(
onPressed: _start,
icon: const Icon(Icons.play_arrow),
label: const Text('Start'),
)
else
FilledButton.tonalIcon(
onPressed: _stop,
icon: const Icon(Icons.stop),
label: const Text('Stop'),
),
OutlinedButton.icon(
onPressed: _warming ? null : _warmUpGnss,
icon: const Icon(Icons.satellite_alt),
label: Text(_warming ? 'Warming up...' : 'Warm up GNSS'),
),
IconButton(
onPressed: _refresh,
tooltip: 'Refresh health',
icon: const Icon(Icons.refresh),
),
],
),
const SizedBox(height: 12),
SegmentedButton<TrackingPreset>(
segments: const [
ButtonSegment(value: TrackingPreset.powerSaver, label: Text('Power saver')),
ButtonSegment(value: TrackingPreset.balanced, label: Text('Balanced')),
ButtonSegment(value: TrackingPreset.highAccuracy, label: Text('High accuracy')),
],
selected: {_preset},
onSelectionChanged: (s) => _setPreset(s.first),
),
if (_message.isNotEmpty)
Padding(
padding: const EdgeInsets.only(top: 12),
child: Text(_message, style: TextStyle(color: Theme.of(context).colorScheme.error)),
),
const _Section('Options'),
SwitchListTile(
dense: true,
title: const Text('Robust indoor score'),
subtitle: const Text('IndoorConfig.robust: indoor / outdoor / unknown with hysteresis'),
value: _robustIndoor,
onChanged: (v) {
setState(() => _robustIndoor = v);
unawaited(_applyOptions());
},
),
SwitchListTile(
dense: true,
title: const Text('Leave the parked anchor on an outward trail'),
subtitle: const Text('IndoorConfig.anchorTrailExitEnabled'),
value: _anchorTrailExit,
onChanged: (v) {
setState(() => _anchorTrailExit = v);
unawaited(_applyOptions());
},
),
SwitchListTile(
dense: true,
title: const Text('Low-power silence probe (Android)'),
subtitle: const Text('MotionConfig.stillProbeIntervalMs: 120 s, 20 s probe'),
value: _stillProbe,
onChanged: (v) {
setState(() => _stillProbe = v);
unawaited(_applyOptions());
},
),
const _Section('Position'),
Text(
f == null
? 'No fix yet'
: '${f.latitude.toStringAsFixed(5)}, ${f.longitude.toStringAsFixed(5)} '
'(+/- ${f.accuracy?.toStringAsFixed(1) ?? '?'} m)\n'
'Quality: ${f.quality?.name ?? '-'} Motion: ${f.motionState ?? '-'}\n'
'Indoor: ${f.indoorState?.name ?? '-'} '
'(score ${f.indoorScore.toStringAsFixed(2)})',
),
const _Section('Motion'),
Text(
m == null
? 'No motion update yet'
: '${m.state.name} activity: ${m.activity ?? '-'} drive mode: ${m.driveMode}',
),
const _Section('Heartbeat'),
Text(
hb == null
? 'No heartbeat yet'
: 'At ${TimeOfDay.fromDateTime(hb.timestamp).format(context)}, '
'last fix ${hb.ageMs == null ? '-' : '${(hb.ageMs! / 1000).round()} s'} ago, '
'anchored: ${hb.anchored}, indoor: ${hb.indoorState?.name ?? '-'}',
),
const _Section('Health'),
Text(
'Running: ${h?.isRunning ?? false} Fixes: ${h?.fixCount ?? 0} '
'Low power: ${h?.balancedPriority ?? false}',
),
Text(
'Indoor: ${h?.indoorState?.name ?? '-'} '
'(score ${h?.indoorScore?.toStringAsFixed(2) ?? '-'})',
),
Text(
age == null
? 'Last GNSS fix: never'
: 'Last GNSS fix: ${age.inMinutes} min ago'
'${h!.isGnssDataStale() ? ' (GPS data may be stale)' : ''}',
),
for (final w in h?.warnings ?? const <String>[]) Text('Warning: $w'),
if (warmUp != null) ...[
const _Section('GNSS warm-up'),
Text(warmUp.success ? 'OK' : 'Failed: ${warmUp.reason?.name}'),
Text(
'Time to first fix: ${warmUp.timeToFirstFix?.inSeconds ?? '-'} s, '
'accuracy: ${warmUp.accuracyMeters?.toStringAsFixed(1) ?? '-'} m, '
'satellites used / visible: ${warmUp.satellitesUsed ?? '-'} / '
'${warmUp.satellitesVisible ?? '-'}',
),
Text('Network: ${warmUp.networkAvailable}'),
],
const _Section('Status events'),
if (_events.isEmpty) const Text('None yet'),
for (final e in _events) Text(e, style: Theme.of(context).textTheme.bodySmall),
],
),
);
}
}
class _Section extends StatelessWidget {
const _Section(this.title);
final String title;
@override
Widget build(BuildContext context) => Padding(
padding: const EdgeInsets.only(top: 16, bottom: 4),
child: Text(title, style: Theme.of(context).textTheme.titleMedium),
);
}