![](https://i0.wp.com/devcodelight.com/wp-content/uploads/2023/06/imagen-86.png?resize=952%2C557&ssl=1)
To quickly and easily get the current location, follow these steps:
First, make sure you have added the geolocator
dependency in the pubspec.yaml
file:
geolocator: ^7.0.3
Then, run flutter pub get
to install the dependency.
Next, add the necessary permissions in the AndroidManifest.xml
file:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Then implement the following code, which will request location permissions, get the user’s current position, and display the latitude and longitude coordinates on the screen.
To test the following code, run the application on a physical device or emulator that supports location.
import 'package:flutter/material.dart'; import 'package:geolocator/geolocator.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( home: MyHomePage(), ); } } class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State { String _locationMessage = ''; @override void initState() { super.initState(); _getLocation(); } Future _getLocation() async { try { // Requests location permissions LocationPermission permission = await Geolocator.requestPermission(); if (permission == LocationPermission.denied) { setState(() { _locationMessage = 'Permission denied'; }); return; } scss Copy code // Gets the current position Position position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high, ); setState(() { _locationMessage = 'Lat: ${position.latitude}, Long: ${position.longitude}'; }); } catch (e) { setState(() { _locationMessage = 'Error: $e'; }); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Get Location'), ), body: Center( child: Text(_locationMessage), ), ); } }
I hope this helps. Have a great day!
![](https://i0.wp.com/devcodelight.com/wp-content/uploads/2023/07/cropped-light_logo-5.png?resize=100%2C100&ssl=1)