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:
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 {@overrideWidget build(BuildContext context) {return MaterialApp(home: MyHomePage(),);}}class MyHomePage extends StatefulWidget {@override_MyHomePageState createState() => _MyHomePageState();}class _MyHomePageState extends State {String _locationMessage = '';@overridevoid initState() {super.initState();_getLocation();}Future _getLocation() async {try {// Requests location permissionsLocationPermission permission = await Geolocator.requestPermission();if (permission == LocationPermission.denied) {setState(() {_locationMessage = 'Permission denied';});return;}scssCopy 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'; });}}@overrideWidget build(BuildContext context) {return Scaffold(appBar: AppBar(title: Text('Get Location'),),body: Center(child: Text(_locationMessage),),);}}
I hope this helps. Have a great day!
