background_location_plus 0.0.3
background_location_plus: ^0.0.3 copied to clipboard
Background location tracking plugin (foreground service Android + CoreLocation iOS).
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:background_location_plus/background_location_plus.dart';
void main() => runApp(const MyApp());
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
bool running = false;
String last = '--';
String speed = '--';
String accuracy = '--';
String timestamp = '--';
StreamSubscription<Map<String, dynamic>>? _sub;
@override
void initState() {
super.initState();
_init();
}
Future<void> _init() async {
await BackgroundLocationPlus.initialize();
await BackgroundLocationPlus.configure(
distanceFilter: 5,
timeInterval: 2,
accuracy: "best",
);
_sub = BackgroundLocationPlus.onLocation.listen((loc) {
if (!mounted) return;
setState(() {
last = '${loc['latitude']?.toStringAsFixed(6)}, ${loc['longitude']?.toStringAsFixed(6)}';
speed = '${loc['speed']?.toStringAsFixed(2)} m/s';
accuracy = '${loc['accuracy']?.toStringAsFixed(1)} m';
timestamp = '${loc['timestamp']}';
});
});
}
Future<void> _start() async {
final ok = await BackgroundLocationPlus.requestPermissions();
if (!ok) {
await BackgroundLocationPlus.openAppSettings();
return;
}
final r = await BackgroundLocationPlus.start();
setState(() => running = r);
}
Future<void> _stop() async {
final r = await BackgroundLocationPlus.stop();
setState(() => running = !r);
}
@override
void dispose() {
_sub?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('BG Location Plus')),
body: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_infoRow('Running', '$running'),
_infoRow('Location', last),
_infoRow('Speed', speed),
_infoRow('Accuracy', accuracy),
_infoRow('Timestamp', timestamp),
const SizedBox(height: 24),
ElevatedButton(onPressed: _start, child: const Text('Start')),
const SizedBox(height: 8),
ElevatedButton(onPressed: _stop, child: const Text('Stop')),
],
),
),
),
);
}
Widget _infoRow(String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label, style: const TextStyle(fontWeight: FontWeight.bold)),
Flexible(child: Text(value, textAlign: TextAlign.end)),
],
),
);
}
}