Skip to main content

How to Request Location permission in Flutter | Latest Version | Android Location Enable 2022

How to Request Location permission in Flutter | Latest Version | Android Location Enable 2022







Location permission is needed when we want our device to fetch the location of user's device to know the location and perform the required actions or work efficiently.
In Flutter we can implement this using Location Permission and asking user to enable the location permission at run time.


Flutter Packages required are:
1. Geolocator
2. Geocoding
You can find these packages on pub.dev site. 

Source code:


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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final geolocator =
      Geolocator.getCurrentPosition(forceAndroidLocationManager: true);
  Position _currentPosition;
  String currentAddress = "";

  void getCurrentLocation() {
    Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
        .then((Position position) {
      setState(() {
        _currentPosition = position;
      });

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

  void getAddressFromLatLng() async {
    try {
      List<Placemark> p = await placemarkFromCoordinates(
          _currentPosition.latitude, _currentPosition.longitude);

      Placemark place = p[0];

      setState(() {
        currentAddress =
            "${place.thoroughfare},${place.subThoroughfare},${place.name}, ${place.subLocality}";
      });
    } catch (e) {
      print(e);
    }
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Location"),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
                decoration: BoxDecoration(
                  color: Theme.of(context).canvasColor,
                ),
                padding: EdgeInsets.symmetric(horizontal: 16, vertical: 8),
                child: Column(
                  children: <Widget>[
                    Row(
                      children: <Widget>[
                        Icon(Icons.location_on),
                        SizedBox(
                          width: 8,
                        ),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: <Widget>[
                              ElevatedButton(
                                child: Text(
                                  'Get Location',
                                  style: Theme.of(context).textTheme.caption,
                                ),
                                onPressed: getCurrentLocation,
                              ),
                              if (_currentPosition != null &&
                                  currentAddress != null)
                                Text(currentAddress,
                                    style: TextStyle(fontSize: 20.0))
                              else
                                Text("Could'nt fetch the location"),
                            ],
                          ),
                        ),
                        SizedBox(
                          width: 8,
                        ),
                      ],
                    ),
                  ],
                ))
          ],
        ),
      ),
    );
  }
}





Like, Share, and Subscribe to the channel.
Thank You.



Comments

Popular posts from this blog

Request Storage Permission in Flutter

 How to Request Storage Permission in Flutter Storage permission is needed when we want the user's device to access the media or files and to perform required actions or work efficiently. In Flutter we can implement this using Storage Permission and asking user to enable the storage permission at run time. Flutter Packages required is: Permission Handler You can find these packages on pub.dev site.  Source Code: import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:permission_handler/permission_handler.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget {   @override   _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> {   Future<int> storagePermissionChecker;   Future<int> checkStoragePermission() async {     final result = await PermissionHandler()         .checkPermissionStatus(PermissionGroup.storage);     setState(() {});     if (re

3D Printing Technology Nowadays

More durable prosthetics and medical devices for patients and stronger parts for airplanes and automobiles are just some of the products that could be created through a new 3D printing technology invented by a UMass Lowell researcher. Substances such as plastics, metals and wax are used in 3D printers to make products and parts for larger items, as the practice has disrupted the prototyping and manufacturing fields. Products created through the 3D printing of plastics include everything from toys to drones. While the global market for 3D plastics printers is estimated at $4 billion and growing, challenges remain in ensuring the printers create objects that are produced quickly, retain their strength and accurately reflect the shape desired, according to UMass Lowell's David Kazmer, a plastics engineering professor who led the research project. Called injection printing, the technology Kazmer pioneered is featured in the academic journal Additive Manufacturing posted online la