5.3 C
New York
Tuesday, December 6, 2022

How to get user current location in Flutter

This is a short guide to getting the user’s current location in Flutter by using a plugin called location.

Installation

1. Add location and its latest version to the dependencies section in your pubspec.yaml file by running the command below:Advertisements

flutter pub add location

2. Perform the following to make sure the package was pulled to your project:

flutter pub get

3. Import the plugin into your Dart code:

import 'package:location/location.dart';

We’re not done and have to add some special setup.

iOS permission setup

AdvertisementsAdd the following to the dict section in your <project-root>/ios/Runner/Info.plist:

<key>NSLocationWhenInUseUsageDescription</key>
<string>Some description</string>

Here’s mine:

Android permission setup

No extra setup is required if you’re using Flutter 1.12 or beyond. However, if your app needs to access location in background mode, you have to place the following permissions in your AndroidManifest.xml:

<uses-permission android_name="android.permission.FOREGROUND_SERVICE" />
    <uses-permission android_name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

The Complete Example

App Preview

Advertisements

This tiny sample app contains a button in the center of the screen. When this button gets pressed, the current longitude and latitude will be returned (for the first time use, a dialog asking permission will appear).

Here’s how it works:

The Code

The full source code in main.dart with explanations:

// main.dart
import 'package:flutter/material.dart';
import 'package:location/location.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      // Remove the debug banner
      debugShowCheckedModeBanner: false,
      title: 'Kindacode.com',
      home: HomePage(),
    );
  }
}

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

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

class _HomePageState extends State<HomePage> {
  late bool _serviceEnabled;
  late PermissionStatus _permissionGranted;
  LocationData? _userLocation;

  Future<void> _getUserLocation() async {
    Location location = Location();

    // Check if location service is enable
    _serviceEnabled = await location.serviceEnabled();
    if (!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return;
      }
    }

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

    final _locationData = await location.getLocation();
    setState(() {
      _userLocation = _locationData;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
                onPressed: _getUserLocation,
                child: const Text('Check Location')),
            const SizedBox(height: 25),
            // Display latitude & longtitude
            _userLocation != null
                ? Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Wrap(
                      children: [
                        Text('Your latitude: ${_userLocation?.latitude}'),
                        const SizedBox(width: 10),
                        Text('Your longtitude: ${_userLocation?.longitude}')
                      ],
                    ),
                  )
                : Container()
          ],
        ),
      ),
    );
  }
}

Conclusion

You’ve learned how to retrieve the longitude and latitude of the current user. If you’d like to explore more amazing and new things about modern mobile development with Flutter, take a look at the following articles:

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Advertisements

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles