How to Get Current Location in Flutter

Flutter is one of the most popular frameworks for cross-platform app development, and many apps today require location services to deliver personalized experiences. In this guide, we will explore how to get the current location in Flutter, ensuring accuracy and security while adhering to best practices.


Understanding Location Services in Flutter

Before we dive into implementation, it’s essential to understand the core concepts of location services in Flutter. Flutter integrates seamlessly with device hardware to fetch GPS and network-based location data. Here are the essential components:

  1. Permission Handling: Ensures the app requests and manages location permissions securely.
  2. Location Plugins: Libraries such as geolocator and location provide the functionality to fetch user location.
  3. Error Handling: Addressing issues like denied permissions or unavailable location data.
  4. Privacy and Security: Complying with policies like GDPR by securing user data.

Also Read :- How to Change Font Family in Flutter


Installing Required Packages

To get started with fetching the current location in Flutter, you need to install specific packages. Below is a step-by-step guide:

  1. Open your pubspec.yaml file.
  2. Add the following dependencies:
  dependencies:
    flutter:
      sdk: flutter
    geolocator: ^9.0.0
    permission_handler: ^11.0.0
  1. Run flutter pub get to fetch the packages.

These packages will enable your app to access location services and handle permissions efficiently.

Also Read :- How to Format DateTime in Flutter


Setting Up Permissions

For both Android and iOS, you need to configure permissions manually in your project files.

For Android

  1. Open android/app/src/main/AndroidManifest.xml.
  2. Add the following permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
  1. If targeting Android 10 or higher, include foreground service permissions:
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

For iOS

  1. Open ios/Runner/Info.plist.
  2. Add the following keys:
<key>NSLocationWhenInUseUsageDescription</key>
<string>We need your location to provide better services.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Location access is required for background features.</string>

Also Read :- How to Install Flutter for MAC


Implementing Current Location Fetching

Below is a code example to fetch the current location using the geolocator plugin.

Code Example

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

class CurrentLocation extends StatefulWidget {
  @override
  _CurrentLocationState createState() => _CurrentLocationState();
}

class _CurrentLocationState extends State<CurrentLocation> {
  String location = 'Fetching location...';

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

  Future<void> getCurrentLocation() async {
    bool serviceEnabled;
    LocationPermission permission;

    serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      setState(() => location = 'Location services are disabled.');
      return;
    }

    permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        setState(() => location = 'Location permission denied.');
        return;
      }
    }

    if (permission == LocationPermission.deniedForever) {
      setState(() => location = 'Location permissions are permanently denied.');
      return;
    }

    Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    setState(() => location = '${position.latitude}, ${position.longitude}');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Current Location')),
      body: Center(child: Text(location)),
    );
  }
}

Explanation:

  1. Permission Checks: Ensures the app has the required permissions before accessing location data.
  2. Location Fetching: Uses Geolocator.getCurrentPosition for high-accuracy results.
  3. Error Handling: Provides user-friendly feedback for disabled services or denied permissions.

Also Read :- How to Embed YouTube Video in Flutter


Handling Errors and Edge Cases

When implementing location services, it’s crucial to handle common issues gracefully:

  • Service Unavailability: Prompt the user to enable location services.
  • Permission Denied: Guide users to app settings to grant permissions.
  • Timeouts: Set reasonable time limits for location fetching to avoid app freezes.
  • Battery Optimization: Minimize resource usage by fetching location only when necessary.

Also Read :- How to Extract Widget in Flutter


Displaying Location on a Map

Integrating maps enhances the user experience. You can use the google_maps_flutter package for this purpose.

Steps to Integrate Google Maps

  1. Add the google_maps_flutter dependency:
  google_maps_flutter: ^2.0.0
  1. Generate an API key from the Google Cloud Console.
  2. Update the AndroidManifest.xml with your API key:
<meta-data
    android:name="com.google.android.geo.API_KEY"
    android:value="YOUR_API_KEY" />
  1. Update the ios/Runner/AppDelegate.swift file for iOS integration.
  2. Display the current location on a map:
GoogleMap(
  initialCameraPosition: CameraPosition(
    target: LatLng(position.latitude, position.longitude),
    zoom: 15,
  ),
  markers: {
    Marker(
      markerId: MarkerId('currentLocation'),
      position: LatLng(position.latitude, position.longitude),
    ),
  },
);

Best Practices for Location-Based Apps

  1. Minimize Permission Scope: Request only the permissions you need.
  2. Educate Users: Clearly explain why location data is required.
  3. Secure Data: Use encryption to protect sensitive information.
  4. Test Thoroughly: Validate location accuracy across various devices and conditions.
  5. Battery Optimization: Avoid frequent location updates unless necessary.

Also Read :- How to Get Data from API in Flutter


Sample Use Cases

Use Case Description
Ride-Sharing Apps Fetch real-time location for route optimization.
Food Delivery Services Track user and delivery agent locations.
Fitness Applications Measure distances traveled during workouts.
Weather Apps Provide location-based weather updates.
Tourism Applications Display nearby attractions and guide routes.

FAQs

  1. How do I fetch the current location in Flutter?
    Use the geolocator package to fetch location data after ensuring permissions are granted.
  2. Why is my location fetching slow?
    It could be due to low GPS signal or insufficient accuracy settings.
  3. How do I handle denied permissions?
    Prompt users to enable permissions from the app settings page.
  4. Is Flutter suitable for location-based apps?
    Yes, Flutter offers robust plugins and cross-platform support for such apps.
  5. What is the best location plugin for Flutter?
    Geolocator and location are highly recommended for their features and reliability.
  6. Can I use location services in the background?
    Yes, but it requires additional configurations for Android and iOS.
  7. How do I test location features?
    Use device emulators or simulators with location simulation tools.
  8. Does using location drain the battery?
    Yes, fetching location frequently can drain the battery. Optimize usage for better performance.
  9. How accurate is Flutter’s location fetching?
    Accuracy depends on the device and settings. High accuracy is achievable with GPS.
  10. How do I show location on a map?
    Use the google_maps_flutter package to integrate maps into your Flutter app.
  11. Can I fetch location without internet?
    Yes, GPS-based location works offline, but accuracy might be lower.
  12. What are the privacy considerations?
    Avoid collecting unnecessary data and inform users about your privacy policies.
  13. How do I enable location services?
    Guide users to enable GPS in device settings if it’s disabled.
  14. What’s the difference between ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION?
    ACCESS_FINE_LOCATION provides precise location, while ACCESS_COARSE_LOCATION offers approximate location.
  15. Can I get location updates continuously?
    Yes, use streams provided by plugins like geolocator for continuous updates.
  16. What is reverse geocoding?
    Converting coordinates into human-readable addresses using APIs.
  17. How do I optimize for battery life?
    Fetch location only when necessary and avoid high accuracy settings unless required.
  18. Is Google Maps API necessary for Flutter?
    Only if you want to display maps or use advanced location services.
  19. What’s the easiest way to debug location issues?
    Check permissions, ensure location services are enabled, and use logs for debugging.
  20. Can I fetch the current speed of the device?
    Yes, the geolocator package provides speed along with location data.
Nishant Sharma
Latest posts by Nishant Sharma (see all)

Leave a Comment