0

I'm using geolocator: ^6.1.1 in flutter I have 2 codes here the first work with no problem

    Position position = await Geolocator.getLastKnownPosition();

but I'm trying to use the current location not the last known and this dont work

    Position position = await Geolocator.getCurrentPosition();

please explain the problem to me, and here is my full code

void _getCurrentLocation() async {
    print('start geo');
    Position position = await Geolocator.getLastKnownPosition();
    // Position position = await Geolocator.getCurrentPosition();
    print(position);
  }

and here is my log

I/flutter (27711): start geo
E/flutter (27711): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: PlatformException(error, java.lang.Integer cannot be cast to java.lang.String, null, java.lang.ClassCastException: java.lang.Integer cannot be cast to java.la
ng.String
E/flutter (27711):      at com.baseflow.geolocator.location.LocationOptions.parseArguments(LocationOptions.java:11)
E/flutter (27711):      at com.baseflow.geolocator.MethodCallHandlerImpl.onGetCurrentPosition(MethodCallHandlerImpl.java:163)
E/flutter (27711):      at com.baseflow.geolocator.MethodCallHandlerImpl.onMethodCall(MethodCallHandlerImpl.java:65)
E/flutter (27711):      at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
E/flutter (27711):      at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/flutter (27711):      at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:692)
E/flutter (27711):      at android.os.MessageQueue.nativePollOnce(Native Method)
E/flutter (27711):      at android.os.MessageQueue.next(MessageQueue.java:379)
E/flutter (27711):      at android.os.Looper.loop(Looper.java:144)
E/flutter (27711):      at android.app.ActivityThread.main(ActivityThread.java:7529)
E/flutter (27711):      at java.lang.reflect.Method.invoke(Native Method)
E/flutter (27711):      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
E/flutter (27711):      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
E/flutter (27711): )
E/flutter (27711): #0      MethodChannelGeolocator._handlePlatformException (package:geolocator_platform_interface/src/implementations/method_channel_geolocator.dart:204)
E/flutter (27711): #1      MethodChannelGeolocator.getCurrentPosition (package:geolocator_platform_interface/src/implementations/method_channel_geolocator.dart:121)
E/flutter (27711): <asynchronous suspension>
E/flutter (27711): #2      _AddNewWashState._getCurrentLocation (package:drsteam/UI/AddNewWash.dart:62)
E/flutter (27711): <asynchronous suspension>
E/flutter (27711):
Husamuldeen
  • 439
  • 1
  • 8
  • 21
  • Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.best); Try this – Ashok Oct 31 '20 at 17:56
  • didn't work both of Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.best); or Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best); – Husamuldeen Oct 31 '20 at 18:45

2 Answers2

0

We can do that by creating an instance of Geolocator and calling getCurrentPosition

import 'package:geolocator/geolocator.dart';

class YourPage extends StatefulWidget {
  @override
  _YourPageState createState() => _YourPageState();
}

class _YourPageState extends State<YourPage> {
  Position _currentPosition;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          children: <Widget>[
            if (_currentPosition != null)
              Text(
                  "LAT: ${_currentPosition.latitude}, LNG: ${_currentPosition.longitude}"),
            FlatButton(
              onPressed: () {
                _getCurrentLocation();
              },
            ),
          ],
        ),
      ),
    );
  }

  _getCurrentLocation() {
    final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;

    geolocator
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
        .then((Position position) {
      setState(() {
        _currentPosition = position;
      });
    }).catchError((e) {
      print(e);
    });
  }
}
Ashok
  • 3,190
  • 15
  • 31
  • final Geolocator geolocator = Geolocator()..forceAndroidLocationManager; this didn't work according to that the android refusd geolocator.getCurrentPosition and accept Geolocator.getCurrentPosition I run the code and didn't work – Husamuldeen Oct 31 '20 at 18:37
0

In your AndroidManifest add permission

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

initialize variable

 Position _currentPosition;

Current Location Function

_getCurrentLocation() async {

    final snackBar = SnackBar(
      content: Row(
        children: [
          Text("Locating....    ",style: TextStyle(fontSize: 16),),
          Container(height: 20, width: 20, child: CircularProgressIndicator()),
        ],
      ),
      backgroundColor: Colors.greenAccent[700],
    );
    _scaffoldKey.currentState.showSnackBar(snackBar);


    await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
        .then((Position position) {
      setState(() {
        _currentPosition = position;
       print(_currentPosition .latitude);
       print(_currentPosition .longitude);

        final snackBar = SnackBar(content: Text("Located 
        Successfully"),backgroundColor: Colors.greenAccent[700],
        );
        _scaffoldKey.currentState.showSnackBar(snackBar);

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

Call this function in button or in initState(),If above problem occurs just restart the phone After that uninstall the app then run flutter clean and run again

Abhijith
  • 2,227
  • 2
  • 15
  • 39