Get Current Location In Flutter

Hello friends, today in this article I am going to teach you how to get user’s current location in flutter. Its video tutorial is also on my YouTube channel, you can go by clicking here. For this I am going to use a flutter plugin.

So you have to install these two plugins in pubspec.yaml file.

geolocator: ^6.2.0
geocoding: ^1.0.5

Now you have to go android->app->src->main->AndroidManifest.xml

Open the AndroidManifest.xml file add the following line:

<manifest xmlns:android="...">
  <uses-permission android:name="android.permission.INTERNET"/> 

  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> 
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
</manifast>

First of all we have to know the latitude and longitude for the location.

 Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best,     forceAndroidLocationManager: true)
        .then((Position position) {
      setState(() {
        _currentPosition = position;
        _getAddressFromLatLng();
      });
      print(_currentPosition);

    }).catchError((e) {
      print(e);
    });

Once we have got the latitude and longitude, now we can easily get its address.

try {
      List<Placemark> placemarks = await placemarkFromCoordinates(
          _currentPosition.latitude,
          _currentPosition.longitude
      );

      Placemark place = placemarks[0];

      setState(() {
        _currentAddress = " ${place.street},  ${place.locality}    ,${place.subAdministrativeArea},${place.administrativeArea}, ${place.postalCode}, ${place.country}";
        print(_currentAddress);
        
      });
 } catch (e) {
      print(e);
}

Full Code

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



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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
         primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Location'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;


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

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  String _currentAddress="";
  late Position _currentPosition;
  void _incrementCounter() {
    setState(() {
     _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(

        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              _currentAddress,
            ),

          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed:(){
          latandlon();
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }


  void latandlon(){
    Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best,     forceAndroidLocationManager: true)
        .then((Position position) {
      setState(() {
        _currentPosition = position;
        _getAddressFromLatLng();
      });
      print(_currentPosition);

    }).catchError((e) {
      print(e);
    });
  }

  _getAddressFromLatLng() async {
    try {
      List<Placemark> placemarks = await placemarkFromCoordinates(
          _currentPosition.latitude,
          _currentPosition.longitude
      );

      Placemark place = placemarks[0];

      setState(() {
        _currentAddress = " ${place.street},  ${place.locality}    ,${place.subAdministrativeArea},${place.administrativeArea}, ${place.postalCode}, ${place.country}";
        print(_currentAddress);

      });
    } catch (e) {
      print(e);
    }
  }
}
Hey folks, I'm Vivek Kumar Pandey, a software engineer with a passion for crafting elegant solutions to complex problems. From the bustling streets of Mumbai to the heart of Bangalore's tech scene, I've journeyed through the world of programming, leaving my mark one line of code at a time. Join me as I continue to explore, innovate, and push the boundaries of what's possible in the digital realm.

Related Posts

Automatically Launch Your Android App on Device Boot Using Java

Creating an Android app that automatically starts after the device reboots can be essential for many applications, such as reminders, alarms, or persistent background services. This article…

Automatically Launch Your Android App on Device Boot – Flutter

Making an Android app that launches automatically upon device reboots can be very helpful for many apps, including background persistent services, alarms, and reminders. We’ll walk you…

Tables in Flutter PDF library

Hello Guys’ in this tutorial, I will teach you how to create a dynamically table in flutter pdf. I will use a plugin for this. Many times it happens…

CERTIFICATE_VERIFY_FAILED Error while performing a POST Request In Flutter

When Sending a post request in Dart. It is giving a response when We test it on API testing tools such as Postman. But when We run…

Best Way To Use SharedPreferences In Flutter

In Flutter’s mobile application, if we have to store some value permanently in the mobile device itself, while the user does not clear the data of the…

Leave a Reply

Your email address will not be published. Required fields are marked *