Flutter Location

repository·master·Indexed 22 days ago

https://github.com/lyokone/flutterlocation

A cross-platform plugin providing a unified API for accessing GPS coordinates, real-time location streams, and background tracking. It supports Android, iOS, macOS, Web, Windows, and Linux. Key features include one-time and continuous location updates, permission handling via PermissionStatus, and configurable precision levels through LocationAccuracy. Background updates are specifically supported on Android and iOS.

Tokens
16.2K
Snippets
58
Records
74
Agent score
77%

What's inside flutterlocation

  1. Overview of Flutter Location features

    master

    Flutter Location is a cross-platform plugin designed for real-time device location access. Key capabilities include:

    • Automatic Permissions: Handles requesting location permissions and enabling GPS automatically.
    • Configurability: Highly configurable settings to balance performance and battery life.
    • Android Compatibility: Works both with and without Google Play Services.
    • Background Support: Supports background location updates.
    • Platform Support: Android, iOS, macOS, Web, Windows, and Linux.
  2. Platform support and feature availability

    master

    Flutter Location supports Android, iOS, macOS, Web, Windows, and Linux. Note that background tracking and location streams have varying support across platforms.

    FeatureAndroidiOSmacOSWebWindowsLinux
    One-time location
    Location stream
    Background updates
    Permission handling

    Platform Notes:

    • Windows: Uses Windows.Devices.Geolocation. Requires system location services to be enabled.
    • Linux: Uses GeoClue2 over D-Bus. Requires system location services to be enabled.
    • Background Updates: Only supported on Android and iOS.
  3. Use backgroundInterval for Android battery optimization

    master

    On Android, you can use the backgroundInterval parameter in changeSettings to reduce the frequency of location polling while your app is in the background.

    When backgroundInterval is provided, the location service will automatically switch to this interval once you call enableBackgroundMode(enable: true) and will switch back to the standard interval once background mode is disabled. This allows for high-frequency updates while the app is in the foreground and low-frequency updates to save battery while in the background.

  4. How to handle continuous background tracking on iOS and macOS

    master

    On iOS and macOS, the underlying Core Location manager uses a battery-saving heuristic that may pause location updates if the device appears to have stopped moving. This can cause unexpected stops in updates for apps requiring continuous live tracking.

    To prevent the system from automatically pausing updates, set pausesLocationUpdatesAutomatically to false within the changeSettings method.

    Note: This behavior depends on the device's movement and does not follow a fixed timeout.

    await location.changeSettings(pausesLocationUpdatesAutomatically: false);
  5. How permissions work in Flutter Location

    master

    By default, flutterlocation handles permissions automatically. The first time you call getLocation or onLocationChanged, the package will automatically trigger the system permission request.

    If you need to manage the permission lifecycle manually (e.g., to show custom UI or rationale before requesting), you can use the hasPermission and requestPermission methods.

    // Automatic permission request happens on these calls:
    final location = Location();
    final position = await location.getLocation();
    
    // Or via stream:
    location.onLocationChanged.listen((position) {
      // ...
    });
  6. Android fallback for devices without Google Play services

    master

    On Android, the plugin defaults to the Google Play services fused location provider.

    Fallback Behavior: On devices without Google Play services (e.g., Huawei devices, AOSP builds, or certain Chinese ROMs), the plugin automatically falls back to the Android framework LocationManager using GPS and network providers. Methods like getLocation, getLastKnownLocation, and onLocationChanged will continue to work and return the same LocationData type.

    Important Limitation: On non-GMS (Google Mobile Services) devices, requestService() cannot display the Google Play services in-app "turn on location" dialog. If the location service is disabled, the plugin reports the service as disabled, and you should direct the user to the system location settings manually.

  7. Install and configure Flutter Location on Windows

    master

    The plugin works out of the box on Windows using the Windows.Devices.Geolocation APIs.

    Requirements & Configuration:

    1. Permissions: The plugin automatically prompts the user for location access upon the first attempt to use location services.
    2. System Settings: Ensure that Location is enabled in the Windows privacy settings for the application to function correctly.
  8. Enable Location in App Sandbox for macOS

    master

    If your macOS application is sandboxed, you must explicitly enable location access in Xcode:

    1. Open your project in Xcode and select your application's target in the project navigator.
    2. Navigate to the Signing & Capabilities tab.
    3. Ensure App Sandbox is turned on.
    4. Expand the App Sandbox section by clicking the ">" button.
    5. In the App Data section, check the box for Location.
  9. Set notification icons using Flutter IconData (without drawables)

    master

    If you do not want to add manual drawable resources to your Android project, you can use iconBytes or imageBytes to pass PNG data directly. This is useful for using Flutter's Icons library.

    Note: When both a name and bytes are provided for the same icon, the bytes take precedence. For the small icon, Android expects a white silhouette on a transparent background to allow for system tinting.

    Future<Uint8List> iconDataToPngBytes(IconData icon, {double size = 24, Color color = Colors.white}) async {
      final recorder = PictureRecorder();
      final canvas = Canvas(recorder);
      final painter = TextPainter(textDirection: TextDirection.ltr)
        ..text = TextSpan(
          text: String.fromCharCode(icon.codePoint),
          style: TextStyle(
            fontSize: size,
            fontFamily: icon.fontFamily,
            package: icon.fontPackage,
            color: color,
          ),
        )
        ..layout();
      painter.paint(canvas, Offset.zero);
      final image = await recorder.endRecording().toImage(size.ceil(), size.ceil());
      final bytes = await image.toByteData(format: ImageByteFormat.png);
      return bytes!.buffer.asUint8List();
    }
    
    await location.changeNotificationOptions(
      iconBytes: await iconDataToPngBytes(Icons.location_on),
    );
  10. Enable background location tracking

    master

    To receive location updates while the app is in the background, you must enable background mode using enableBackgroundMode(enable: true).

    Android Specifics

    • Notifications: Enabling background mode on Android triggers a notification. You can customize this via changeNotificationOptions.
    • Permissions: By default, enableBackgroundMode requests ACCESS_BACKGROUND_LOCATION ("Allow all the time") on Android.
    • Bypassing strict permission: If you only need updates while a foreground service notification is visible, you can skip the "Allow all the time" prompt by setting requireBackgroundPermission: false. This allows you to start the foreground service using only standard fine/coarse location permissions.
    await location.enableBackgroundMode(
      enable: true,
      requireBackgroundPermission: false,
    );