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

discontinued

A Flutter package for implementing location sharing with foreground streams and periodic background updates.

vk_location_sharing #

Pub Version License

A powerful and flexible Flutter package for implementing real-time location sharing with both foreground streams and periodic background updates. It provides a clean, unified API to handle permissions and location tracking with ease.

โœจ Features #

  • โœ… Single Initialize Function: Call initialize() once in your main.dart to set up everything
  • ๐ŸŽฏ Unified Location Sharing: Simple shareLocation() method that handles all permissions and starts tracking
  • ๐Ÿ“ Real-time Foreground Stream: Live location updates as the user moves
  • ๐Ÿ”„ Periodic Background Updates: Regular location tracking even when app is backgrounded (via Workmanager)
  • ๐Ÿ”€ Flexible Stream Handling: Choose to handle foreground and background updates separately or combined
  • ๐ŸŽ›๏ธ Custom Callbacks: Execute custom code with each location update (e.g., send to backend)
  • ๐Ÿ” Built-in Permission Handling: Automatic permission request and verification
  • โš™๏ธ Highly Configurable: Customize accuracy, distance filters, update frequency, and more
  • ๐Ÿ“ฑ Battery Optimized: Uses distance filters to minimize battery drain
  • ๐Ÿงช Well Tested: Comprehensive unit tests with mocking support

๐Ÿ“ฆ Installation #

Add vk_location_sharing to your pubspec.yaml:

dependencies:
  vk_location_sharing: ^1.0.0

Then run:

flutter pub get

๐Ÿ”ง Platform Setup #

iOS #

Add the following keys to your Info.plist file (or use Xcode UI):

<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs access to your location to share it with others.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>This app needs access to your location at all times to share it with others.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>This app needs access to your location at all times to share it with others.</string>

For background location tracking, add to Info.plist:

<key>UIBackgroundModes</key>
<array>
  <string>location</string>
  <string>fetch</string>
</array>

Android #

Add permissions to android/app/src/main/AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

For background services to work properly on Android 12+, add to your app's build.gradle:

android {
  compileSdkVersion 33
  // ...
}

๐Ÿš€ Quick Start #

Basic Usage #

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(const MyApp());
}

class MyHomePage extends StatefulWidget {
  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _vkLocation = VkLocationSharing();
  Position? _currentPosition;
  bool _isSharing = false;

  @override
  void initState() {
    super.initState();
    _initializeLocation();
  }

  Future<void> _initializeLocation() async {
    // Initialize the package once in your app
    await _vkLocation.initialize(
      config: LocationConfig(
        accuracy: LocationAccuracy.best,
        distanceFilter: 5, // Update every 5 meters
        backgroundUpdateFrequency: const Duration(minutes: 15),
      ),
    );

    // Listen to location updates
    _vkLocation.foregroundLocationStream.listen((position) {
      setState(() {
        _currentPosition = position;
      });
    });
  }

  Future<void> _toggleSharing() async {
    if (!_isSharing) {
      final success = await _vkLocation.shareLocation();
      if (success) {
        setState(() => _isSharing = true);
      }
    } else {
      await _vkLocation.stopSharing();
      setState(() => _isSharing = false);
    }
  }

  @override
  void dispose() {
    _vkLocation.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Location Sharing')),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            if (_currentPosition != null)
              Text('Lat: ${_currentPosition!.latitude}\nLng: ${_currentPosition!.longitude}')
            else
              const Text('No location data'),
            const SizedBox(height: 20),
            ElevatedButton(
              onPressed: _toggleSharing,
              child: Text(_isSharing ? 'Stop Sharing' : 'Start Sharing'),
            ),
          ],
        ),
      ),
    );
  }
}

๐Ÿ“š Advanced Usage #

Separate Foreground and Background Streams #

await _vkLocation.initialize(
  config: LocationConfig(
    handleForegroundAndBackgroundSeparately: true,
    accuracy: LocationAccuracy.best,
    distanceFilter: 5,
    backgroundUpdateFrequency: const Duration(minutes: 15),
  ),
);

// Listen to foreground updates
_vkLocation.foregroundLocationStream.listen((position) {
  print('Foreground: ${position.latitude}');
});

// Listen to background updates separately
_vkLocation.backgroundLocationStream.listen((position) {
  print('Background: ${position.latitude}');
});

Custom Location Handler #

await _vkLocation.initialize(
  config: LocationConfig(
    accuracy: LocationAccuracy.best,
    onLocationUpdate: (position, {required isBackground}) async {
      // Send to your backend API
      if (isBackground) {
        await sendLocationToBackend(position, background: true);
      } else {
        await sendLocationToBackend(position, background: false);
      }
    },
  ),
);

Selective Sharing #

// Start only foreground sharing
await _vkLocation.shareLocation(includeForeground: true, includeBackground: false);

// Start only background sharing
await _vkLocation.shareLocation(includeForeground: false, includeBackground: true);

// Stop only background sharing
await _vkLocation.stopSharing(stopForeground: false, stopBackground: true);

๐ŸŽฏ Configuration Options #

The LocationConfig class provides these customization options:

Parameter Type Default Description
handleForegroundAndBackgroundSeparately bool false If true, use separate streams for foreground/background. If false, all updates go to foreground stream.
accuracy LocationAccuracy high Desired GPS accuracy (high, best, low, lowest)
distanceFilter int 0 Minimum distance in meters between updates
backgroundUpdateFrequency Duration 15 minutes Frequency of background updates
onLocationUpdate Function null Custom callback executed with each location update

๐Ÿ“ก API Reference #

VkLocationSharing #

initialize({required LocationConfig config})

Initializes the package with configuration. Must be called before shareLocation().

shareLocation({bool includeForeground = true, bool includeBackground = true})

Starts location sharing after requesting necessary permissions.

  • Returns: bool - true if permissions granted and tracking started, false otherwise
  • Parameters:
    • includeForeground: Enable foreground location tracking
    • includeBackground: Enable background location tracking

stopSharing({bool stopForeground = true, bool stopBackground = true})

Stops location sharing.

foregroundLocationStream

Stream of foreground location updates.

backgroundLocationStream

Stream of background location updates (if handleForegroundAndBackgroundSeparately is true).

getCurrentLocation()

Fetch current location once.

dispose()

Clean up resources and close all streams.

โš ๏ธ Important Notes #

Background Update Frequency: Background updates are handled via Workmanager. The minimum frequency on most platforms is 15 minutes. This is a platform limitation, not a package limitation.

Battery Usage: Use the distanceFilter parameter to reduce update frequency and save battery. For example, set it to 10-50 meters for reasonable accuracy with minimal battery drain.

Permission Handling: Always handle cases where permissions are denied. The shareLocation() method returns false if permissions are not granted.

Cleanup: Always call dispose() in your widget's dispose method to prevent memory leaks.

๐Ÿ› Troubleshooting #

Background location not updating #

  • Ensure ACCESS_BACKGROUND_LOCATION permission is granted on Android
  • Check that background modes are enabled in iOS Info.plist
  • Verify workmanager is initialized properly during initialize() call

Foreground stream not emitting #

  • Ensure location services are enabled on the device
  • Check that foreground location permission is granted
  • Verify you called initialize() before shareLocation()

App crashes on background updates #

  • Ensure all plugins used in the callback are background-safe
  • Use kDebugMode checks for debug logging to avoid issues

๐Ÿ“„ License #

MIT License - see LICENSE file for details.

๐Ÿ‘ฅ Contributing #

Contributions are welcome! Please feel free to submit a pull request.

๐Ÿ“ž Support #

For issues, questions, or suggestions, please visit the GitHub repository.

0
likes
0
points
11
downloads

Publisher

unverified uploader

Weekly Downloads

A Flutter package for implementing location sharing with foreground streams and periodic background updates.

Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

flutter, geolocator, shared_preferences, workmanager

More

Packages that depend on vk_location_sharing