Flutter how to get latitude, longitude using geolocator package?

Viewed 1570

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'),
       ),
     ),
   );
 }
} ```
1 Answers

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'),
),
Related