Flutter how to get latitude, longitude using geolocator package?

850

It should be position.latitude or position.longitude. You've used position.longitude() & position.latitude(), which is incorrect.

Also, you need to add async-await for onPressed callback. I'm assuming that you've added permissions in manifest & granted the necessary permissions as well.

Method

void getLocation() async {
   Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
   print(position.latitude);
   print(position.longitude);
}

Widget

RaisedButton(
    color: Colors.red,
    onPressed: () async {
        await getLocation();
    },
    child: Text('Get Location'),
),
Share:
850
lQsdY8
Author by

lQsdY8

Updated on December 27, 2022

Comments

  • lQsdY8
    lQsdY8 over 1 year

    Flutter how to get latitude, longitude using geolocator package? Already gave permissions both android and ios, downloaded package using pubspec.yaml. I don't understand why can't print longitude and latitude to console? tried write print(position), print(position.longitude()), print(position.latitue()).

    import 'package:flutter/material.dart';
    import 'package:geolocator/geolocator.dart';
    
    
    class LoadingScreen extends StatefulWidget {
     @override
     _LoadingScreenState createState() => _LoadingScreenState();
    }
    
    class _LoadingScreenState extends State<LoadingScreen> {
     void getLocation() async {
       print('Printing text before getCurrentLocation()');
       Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
       print(position);
    
    
    }
    
     @override
     Widget build(BuildContext context) {
       return Scaffold(
         body: Center(
           child: RaisedButton(
             color: Colors.red,
             onPressed: () {
               getLocation();
             },
             child: Text('Get Location'),
           ),
         ),
       );
     }
    } ```
    
  • lQsdY8
    lQsdY8 about 3 years
    thank you after added async, await to onPressed. Everything worked.
  • Tirth Patel
    Tirth Patel about 3 years
    That's awesome! I'm glad I could help. You can mark it as accepted if it answers your question.