X
    Categories: Flutter

Flutter location: How to Fetch Current Latitude and Longitude

 

Flutter Location :

Flutter location provides the user current latitude and longitude positions so that we can trace the user current address accurately.

You might have noticed now a days every app which provides user a door delivery services like amazon, flipkart, e-bay accepts the user location automatically using these positions.

Also food delivery apps like swiggy, zomato, food panda provide home delivery of food easily using this locations points also you can track the delivery agent on a map so that you can know his / her exact location.

With the help of user and agent location points i.e., latitude and longitude we can calculate time required to reach the destination which is displayed on the app.

There are many more advantages of using them in car / bike rental apps like uber, ola and so on…We can also find the places on google maps using these points.

Let’s get started now…

 

Flutter Location Video tutorial :

Go through the below tutorial for more interesting updates.

 

pubspec.yaml :

Add a location dependency in pubspec also provide the location dependency plugin version latest available.

dev_dependencies:
  flutter_test:
    sdk: flutter
  location:

 


 

GetLocationWidget.dart:

 

Create a class GetLocationWidget extending StatefulWidget.

class GetLocationWidget extends StatefulWidget {
  const GetLocationWidget({Key key}) : super(key: key);

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

 

 

Declare variables and provide objects for the class location and a String to display error message.

final Location location = Location();
LocationData _location;
String _error;

 

 

Specify a async method to fetch flutter location details of the device/user.

Future<void> _getLocation() async {
  setState(() {
    _error = null;
  });

  try {
    final LocationData _locationResult = await location.getLocation();
    setState(() {
      _location = _locationResult;
    });
  } on PlatformException catch (err) {
    setState(() {
      _error = err.code;
    });
  }
}

 

 

Declare a Text widget to display the flutter location details of the user and specify the text styles

Text(
  'Location: ' + (_error ?? '\n\n' 'Latitude ' + '${_location.latitude}' + '\n\nLongitude ' + '${_location.longitude ?? " - "}'),
  style: TextStyle(
    fontSize: 20,
    color: Colors.black,
    fontWeight: FontWeight.bold,
    fontFamily: "Varela"
  ),
),

 

 

And a Raised button for user to tap for fetching the location details.

Row(
  children: <Widget>[
    Padding(
      padding: const EdgeInsets.all(20.0),
      child: RaisedButton(
        child: const Text('Fetch Location'),
        onPressed: _getLocation,
      ),
    )
  ],
),

 

GetLocationWidget.dart :

Create a class GetLocationWidget using which we can fetch the user location

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

class GetLocationWidget extends StatefulWidget {
  const GetLocationWidget({Key key}) : super(key: key);

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

class _GetLocationState extends State<GetLocationWidget> {
  final Location location = Location();

  LocationData _location;
  String _error;

  Future<void> _getLocation() async {
    setState(() {
      _error = null;
    });

    try {
      final LocationData _locationResult = await location.getLocation();
      setState(() {
        _location = _locationResult;
      });
    } on PlatformException catch (err) {
      setState(() {
        _error = err.code;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: <Widget>[
        Text(
          'Location: ' +
              (_error ??
                  (_location != null
                      ? '\n\nLatitude: ${_location.latitude}\n\nLongitude: ${_location.longitude}'
                      : 'Location not fetched')),
          style: TextStyle(
            fontSize: 20,
            color: Colors.black,
            fontWeight: FontWeight.bold,
            fontFamily: "Varela",
          ),
        ),
        SizedBox(height: 20),
        RaisedButton(
          child: const Text('Fetch Location'),
          onPressed: _getLocation,
        ),
      ],
    );
  }
}

 

 


main.dart :

Initialzie with void main()

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

 

 

Create a class MyApp and return MaterialApp

MaterialApp(
  title: 'Flutter Location',
  debugShowCheckedModeBanner: false,
  theme: ThemeData(
    primarySwatch: Colors.blue,
  ),
  home: const MyHomePage(title: 'Flutter Location Demo'),
);

 

 

Create a state for HomePage class

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

 

 

 

Create a object for Location class

final Location location = Location();

 

 

Here we need to check and request user permission from here

 

Specify the design for displaying the flutter location details here we are calling a widget to display result.

Container(
  padding: const EdgeInsets.all(32),
  child: Column(
    children: const <Widget>[
      GetLocationWidget(),
    ],
  ),
),

 


 

Fullcode :

Providing complete code to enable location detection in your application.

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Location',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Location Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  final Location location = Location();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        padding: const EdgeInsets.all(32),
        child: Column(
          children: const <Widget>[
            GetLocationWidget(),
          ],
        ),
      ),
    );
  }
}

 


 

Flutter location output :

This screen showcases the functionality of flutter location.

 

If you have any questions about this Flutter tutorial, feel free to leave them in the comments section below. If you found this tutorial helpful, please consider liking and sharing it to stay updated with more interesting content.

abhishek:
Related Post

This website uses cookies.