Get Location Details – Latitude and Longitude in Flutter

If we are building some mobile app that needs location details, then we will have to find latitude and longitude values. We can get these values from the GPS data. Since these are the gps cordinates.

For implementing this easily we can make use of the geo location package.

Refer: Adding Location package to Flutter Project

Printing GPS cordinates – Latitude and Longitude for Flutter App

main.dart

import 'package:flutter/material.dart';
import 'package:clima/screens/loading_screen.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark(),
      home: LoadingScreen(),
    );
  }
}

screens/loading_screen.dart

import 'package:flutter/material.dart';
import '../services/location.dart';

class LoadingScreen extends StatefulWidget {
  @override
  _LoadingScreenState createState() => _LoadingScreenState();
}

class _LoadingScreenState extends State<LoadingScreen> {

  @override
  void initState() {

    getLocation();
    super.initState();
  }

  void getLocation() async{
    Location location = new Location();
    await location.getCurrentLocation();
    print(location.latitude);
    print(location.longitude);

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold();
  }
}

services/location.dart

import 'package:geolocator/geolocator.dart';

class Location{
  double latitude,longitude;
  Future<void> getCurrentLocation() async {
    try{
      Position position = await Geolocator()
          .getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
      print(position);

      latitude = position.latitude;
      longitude = position.longitude;

    }catch(e){
      print(e);
    }
  }
}

Output:

About the Author: smartcoder

You might like

Leave a Reply

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