arbiter_background_location 1.0.0 copy "arbiter_background_location: ^1.0.0" to clipboard
arbiter_background_location: ^1.0.0 copied to clipboard

A Flutter plugin for background location tracking with Android and iOS support.

example/lib/main.dart

import 'package:flutter/material.dart';
import 'package:arbiter_background_location/arbiter_background_location.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // Initialize the plugin
  await MyBackgroundGeolocation.initialize();
  
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Background Geolocation Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  bool isTracking = false;
  LocationData? currentLocation;
  List<LocationData> locations = [];
  String status = 'Ready';

  @override
  void initState() {
    super.initState();
    _setupLocationListener();
    _loadStoredLocations();
  }

  void _setupLocationListener() {
    MyBackgroundGeolocation.onLocation.listen((location) {
      setState(() {
        currentLocation = location;
        status = 'Location updated: ${location.latitude.toStringAsFixed(6)}, ${location.longitude.toStringAsFixed(6)}';
      });
    });

    MyBackgroundGeolocation.onError.listen((error) {
      setState(() {
        status = 'Error: $error';
      });
    });
  }

  Future<void> _loadStoredLocations() async {
    final storedLocations = await MyBackgroundGeolocation.getLocations(limit: 10);
    setState(() {
      locations = storedLocations;
    });
  }

  Future<void> _startTracking() async {
    final config = MyBackgroundGeolocationConfig(
      interval: 10000, // 10 seconds
      distanceFilter: 50.0, // 50 meters
      desiredAccuracy: 'HIGH',
      apiUrl: 'https://your-api.com/locations',
      userId: 'user123',
      headers: {
        'Authorization': 'Bearer your-token',
      },
    );

    final success = await MyBackgroundGeolocation.start(config);
    if (success) {
      setState(() {
        isTracking = true;
        status = 'Tracking started';
      });
    } else {
      setState(() {
        status = 'Failed to start tracking';
      });
    }
  }

  Future<void> _stopTracking() async {
    final success = await MyBackgroundGeolocation.stop();
    if (success) {
      setState(() {
        isTracking = false;
        status = 'Tracking stopped';
      });
    } else {
      setState(() {
        status = 'Failed to stop tracking';
      });
    }
  }

  Future<void> _getCurrentPosition() async {
    final location = await MyBackgroundGeolocation.getCurrentPosition();
    if (location != null) {
      setState(() {
        currentLocation = location;
        status = 'Current position: ${location.latitude.toStringAsFixed(6)}, ${location.longitude.toStringAsFixed(6)}';
      });
    } else {
      setState(() {
        status = 'Failed to get current position';
      });
    }
  }

  Future<void> _syncToAPI() async {
    setState(() {
      status = 'Syncing to API...';
    });

    final success = await MyBackgroundGeolocation.sync(
      'https://your-api.com/locations',
      userId: 'user123',
      headers: {
        'Authorization': 'Bearer your-token',
      },
    );

    setState(() {
      status = success ? 'Sync completed' : 'Sync failed';
    });
  }

  Future<void> _clearLocations() async {
    final success = await MyBackgroundGeolocation.clearLocations();
    if (success) {
      setState(() {
        locations.clear();
        status = 'Locations cleared';
      });
    } else {
      setState(() {
        status = 'Failed to clear locations';
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Background Geolocation'),
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
      ),
      body: Padding(
        padding: EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            Card(
              child: Padding(
                padding: EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      'Status',
                      style: Theme.of(context).textTheme.titleMedium,
                    ),
                    SizedBox(height: 8),
                    Text(
                      status,
                      style: Theme.of(context).textTheme.bodyMedium,
                    ),
                    SizedBox(height: 16),
                    Row(
                      children: [
                        Expanded(
                          child: ElevatedButton(
                            onPressed: isTracking ? _stopTracking : _startTracking,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: isTracking ? Colors.red : Colors.green,
                              foregroundColor: Colors.white,
                            ),
                            child: Text(isTracking ? 'Stop Tracking' : 'Start Tracking'),
                          ),
                        ),
                        SizedBox(width: 8),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: _getCurrentPosition,
                            child: Text('Get Position'),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 8),
                    Row(
                      children: [
                        Expanded(
                          child: ElevatedButton(
                            onPressed: _syncToAPI,
                            child: Text('Sync to API'),
                          ),
                        ),
                        SizedBox(width: 8),
                        Expanded(
                          child: ElevatedButton(
                            onPressed: _clearLocations,
                            child: Text('Clear Locations'),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(height: 16),
            if (currentLocation != null) ...[
              Card(
                child: Padding(
                  padding: EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Current Location',
                        style: Theme.of(context).textTheme.titleMedium,
                      ),
                      SizedBox(height: 8),
                      Text('Latitude: ${currentLocation!.latitude.toStringAsFixed(6)}'),
                      Text('Longitude: ${currentLocation!.longitude.toStringAsFixed(6)}'),
                      if (currentLocation!.accuracy != null)
                        Text('Accuracy: ${currentLocation!.accuracy!.toStringAsFixed(2)}m'),
                      Text('Time: ${currentLocation!.timestamp.toString()}'),
                    ],
                  ),
                ),
              ),
              SizedBox(height: 16),
            ],
            Expanded(
              child: Card(
                child: Padding(
                  padding: EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Stored Locations (${locations.length})',
                        style: Theme.of(context).textTheme.titleMedium,
                      ),
                      SizedBox(height: 8),
                      Expanded(
                        child: ListView.builder(
                          itemCount: locations.length,
                          itemBuilder: (context, index) {
                            final location = locations[index];
                            return ListTile(
                              title: Text('${location.latitude.toStringAsFixed(6)}, ${location.longitude.toStringAsFixed(6)}'),
                              subtitle: Text('${location.timestamp.toString()}'),
                              trailing: location.accuracy != null
                                  ? Text('${location.accuracy!.toStringAsFixed(0)}m')
                                  : null,
                            );
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}
3
likes
160
points
40
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

A Flutter plugin for background location tracking with Android and iOS support.

Repository (GitHub)
View/report issues

License

MIT (license)

Dependencies

flutter, http, shared_preferences, sqflite

More

Packages that depend on arbiter_background_location