Logo

dev-resources.site

for different kinds of informations.

How to fetch current location of user in Flutter?

Published at
11/17/2021
Categories
flutter
dart
location
Author
shubhamkshatriya25
Categories
3 categories in total
flutter
open
dart
open
location
open
Author
18 person written this
shubhamkshatriya25
open
How to fetch current location of user in Flutter?

Introduction:

There are times when we want to access the end user's GPS location. Be it an E-commerce industry or a food delivery app, accessing the GPS location is needed to offer better user experience and provide better services.

In this article, we will see how to fetch a user's location and display the address in Flutter using the location plugin.

Setup

Go to pubspec.yaml file and add location plugin under dependencies and then run flutter pub get.

dependencies:
  location: ^4.2.0
Enter fullscreen mode Exit fullscreen mode

Android

If the project was created with Flutter 1.12 and above, all dependencies will be installed automatically.

If the project was created before Flutter 1.12, follow the steps below.
Go to android/app/src/main/AndroidManifest.xml and add the following code inside the application tag.

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>
Enter fullscreen mode Exit fullscreen mode

iOS

Go to ios/Runner/Info.plist and add the following permission.

<key>NSLocationWhenInUseUsageDescription</key>
<key>NSLocationAlwaysUsageDescription</key>
Enter fullscreen mode Exit fullscreen mode

With this, we are all set to use the location plugin in our Flutter application.

Implementation

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:geocoder/geocoder.dart';
import 'package:location/location.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Location',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: getLocation(),
    );
  }
}

class getLocation extends StatefulWidget {
  @override
  _MyLocationState createState() => _MyLocationState();
}

class _MyLocationState extends State<getLocation> {
  LocationData _currentPosition;
  String _address;
  Location location = new Location();

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Flutter Location"),
      ),
      body: Container(
        child: SafeArea(
          child: Column(
            children: [
              if (_currentPosition)
                Text(
                  "Latitude: ${_currentPosition.latitude}",
                  style: TextStyle(fontSize: 22, fontWeight: FontWeight.w600),
                ),
              if (_currentPosition)
                Text(
                  "Longitude: ${_currentPosition.longitude}",
                  style: TextStyle(fontSize: 22, fontWeight: FontWeight.w600),
                ),
              if (_address)
                Text(
                  "Address: $_address",
                  style: TextStyle(
                    fontSize: 16,
                  ),
                ),
            ],
          ),
        ),
      ),
    );

  fetchLocation() async {}
  Future<List<Address>> getAddress(double lat, double lang) async {}
  }

Enter fullscreen mode Exit fullscreen mode

Here, we have imported two libraries location and geocoding that will be used to fetch the GPS location and to convert a co-ordinate into Address respectively.

We have also created two functions at the bottom and invoked fetchLocation in the initState() method. When the app will start, it will fetch the GPS location of the user asynchronously and update the Text widget used in the Container.

Let's see how the fetchLocation method will be like.

fetchLocation()

In order to request location, we need to manually check if Location Service status and Permission status are available every time.

If we have both the permissions then only we can fetch the location using the getLocation() method. We can also get continuous callbacks when the position changes using onLocationChanged event listener.

fetchLocation() async {
    bool _serviceEnabled;
    PermissionStatus _permissionGranted;

    _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return;
      }
    }

    _permissionGranted = await location.hasPermission();
    if (_permissionGranted == PermissionStatus.denied) {
      _permissionGranted = await location.requestPermission();
      if (_permissionGranted != PermissionStatus.granted) {
        return;
      }
    }

    _currentPosition = await location.getLocation();
    location.onLocationChanged.listen((LocationData currentLocation) {
      setState(() {
        _currentPosition = currentLocation;
        getAddress(_currentPosition.latitude, _currentPosition.longitude)
            .then((value) {
          setState(() {
            _address = "${value.first.addressLine}";
          });
        });
      });
    });
  }
Enter fullscreen mode Exit fullscreen mode

getAddress()

Once we get the geographic co-ordinates of the user, we use the getAddress() method to parse it into an address.

The geocoder provides a findAddressesFromCoordinates() method for it.

  Future<List<Address>> getAddress(double lat, double lang) async {
    final coordinates = new Coordinates(latitude, longitude);
    List<Address> address =
        await Geocoder.local.findAddressesFromCoordinates(coordinates);
    return address;
  }
}
Enter fullscreen mode Exit fullscreen mode

With this, we have added the location plugin in our Flutter Application. On running the application the output should look like this.

Output

Thanks for the read. I hope this article helped you to get started with Location plugin in Flutter.

You can connect with me on Twitter for any discussion.

Happy Coding!

location Article's
30 articles in total
Favicon
Handling Location Permissions in React Native
Favicon
Realtime Location Tracker & Communications
Favicon
Introducing GroupTrack: Simplified Location-Based Services for Flutter
Favicon
React Native Background Location Tracking
Favicon
Answer: Flutter geolocator package not retrieving location
Favicon
Adding location tracking to mobile apps (for Android)
Favicon
Flutter Backgroud Locator
Favicon
AR Game ~ Geospatial API ~
Favicon
AR Game ~ Location Information ~
Favicon
Unlocking the Power of Geolocation with IPStack's API
Favicon
How to implement UWB precise location system with TDOA technology(1)
Favicon
mylivelocation
Favicon
Expo GPS Location + Task Manager
Favicon
A Realtime location sharing App built with React
Favicon
Developing a Bluetooth Low energy-based application
Favicon
How to get address location from latitude and longitude in Angular15+
Favicon
Laravel 9 Get Current User Location Using IP Address
Favicon
Location without Google Services
Favicon
How to find the folder location of a command in linux?
Favicon
Search the hospitals using Huawei Map Kit, Site Kit and Location Kit in Patient Tracking Android app (Kotlin) – Part 5
Favicon
Add maps and location services to your apps
Favicon
Know your Lagos market. How to create a web map showing images with QGIS and host it for free.
Favicon
How to Automatically Fill Addresses in Lifestyle Apps
Favicon
How to fetch current location of user in Flutter?
Favicon
How To Get Current User Location In Laravel
Favicon
Create your own indoor maps using Azure Maps Creator
Favicon
Anyone Used Locator to find anyone true Location..?
Favicon
How to Get IP Address Information Using Python [2021]
Favicon
Find the Coordinates for a Location
Favicon
Geohash Open-Source library in TSQL for SQL Server

Featured ones: