3

I have old flutter project, I added web support to it, Now ,I am trying to get my Location in flutter web , So i added location to my page. this is my code:

  @override
  void initState() {
    super.initState();
    _getLocation();
  }

  Future _getLocation() async {
    Location location = new Location();

    var _permissionGranted = await location.hasPermission();
    _serviceEnabled = await location.serviceEnabled();

    if (_permissionGranted != PermissionStatus.granted || !_serviceEnabled) {
      _permissionGranted = await location.requestPermission();
      _serviceEnabled = await location.requestService();
    } else {
      print("-----> $_serviceEnabled");

      setState(() {
        _serviceEnabled = true;
        _loading = false;
      });
    }

    try {
      final LocationData currentPosition = await location.getLocation();
      setState(() {
        longitude = currentPosition.longitude.toString();
        latitude = currentPosition.latitude.toString();
        print(
            '${widget.url}?BranchName=&latitude=${latitude}&longitude=${longitude}');
        _loading = false;
      });
    } on PlatformException catch (err) {
      _loading = false;
      print("-----> ${err.code}");
    }
  }

After getting Location permission by chrome,

enter image description here

Nothing happening! In vsCode console i just got this error:

Error: [object GeolocationPositionError]


    at Object.createErrorWithStack (http://localhost:43705/dart_sdk.js:4351:12)
    at Object._rethrow (http://localhost:43705/dart_sdk.js:37962:16)
    at async._AsyncCallbackEntry.new.callback (http://localhost:43705/dart_sdk.js:37956:13)
    at Object._microtaskLoop (http://localhost:43705/dart_sdk.js:37788:13)
    at _startMicrotaskLoop (http://localhost:43705/dart_sdk.js:37794:13)
    at http://localhost:43705/dart_sdk.js:33303:9

**USING @JS('navigator.geolocation')

I also try this, but never success method called and nothing heppen.

Cyrus the Great
  • 5,145
  • 5
  • 68
  • 149

2 Answers2

2

This works now(all platforms including web), June 2021, with the Location package.

final Location location = new Location();
_locationData = await location.getLocation();
print(_locationData.latitude);

See full details here: pub.dev/packages/location

zak
  • 776
  • 10
  • 10
0

Dart currently has an issue with the Geolocation API. Consider writing an interop library or using mine. Link below Geolocation PolyFill

Night King
  • 455
  • 4
  • 12