Geolocator Plugin to get current location

后端 未结 2 791
灰色年华
灰色年华 2021-01-23 18:56

I am using Geolocator plugin to get the current location of the device, and google map plugin to integrate the map widget in the flutter

The google map wor

相关标签:
2条回答
  • 2021-01-23 19:34

    add this package into flutter project.. - pubspec.yaml

    -dependencies:

      location: ^2.3.4
    
    0 讨论(0)
  • 2021-01-23 19:40

    The problem is google_maps_flutter package needs permission for accessing your location but the package has not native codes to ask that permission.

    So you need to write native code or just install another package which is able to take that permission.

    Install this: https://pub.dartlang.org/packages/location

    Then:

    getLocationPermission() async {
        final Location location = new Location();
        try {
          location.requestPermission(); //to lunch location permission popup
        } on PlatformException catch (e) {
          if (e.code == 'PERMISSION_DENIED') {
            print('Permission denied');
          }
        }
      }
    

    Or if you want more solid code, this is my code for some project(with location package):

    //Show some loading indicator depends on this boolean variable
    bool askingPermission = false;
    
    @override
      void initState() {
        this.getLocationPermission();
        super.initState();
      }
    
      Future<bool> getLocationPermission() async {
        setState(() {
          this.askingPermission = true;
        });
        bool result;
        final Location location = Location();
        try {
          if (await location.hasPermission())
            result = true;
          else {
            result = await location.requestPermission();
          }
          print('getLocationPermission: '
              '${result ? 'Access Allowed' : 'Access Denied'}');
        } catch (log, trace) {
          result = false;
          print('getLocationPermission/log: $log');
          print('getLocationPermission/trace: $trace');
        } finally {
          setState(() {
            this.askingPermission = false;
          });
        }
        return result;
      }
    
    0 讨论(0)
提交回复
热议问题