Get user location using flutter - flutter

I'm using the geolocator plugin to access the user's location but it seems like it does not work, cause when I run my code I get the error on message.
I have done all the geolocation configuration, but I have the problem.
Adding the Geolocator plugin(pubspec.yaml)
dependencies:
flutter:
sdk: flutter
geolocator: ^5.1.3
For android, head on over to your AndroidManifest.xml and add either of these permissions:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Source code for getting address
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
Position _currentPosition;
String _currentAddress;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Location"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (_currentPosition != null) Text(_currentAddress),
FlatButton(
child: Text("Get location"),
onPressed: () {
_getCurrentLocation();
},
),
],
),
),
);
}
_getCurrentLocation() {
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
_getAddressFromLatLng();
}).catchError((e) {
print(e);
});
}
_getAddressFromLatLng() async {
try {
List<Placemark> p = await geolocator.placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
_currentAddress =
"${place.locality}, ${place.postalCode}, ${place.country}";
});
} catch (e) {
print(e);
}
}
}
The problem I get when I run my code is here.

Try flutter clean on terminal and then run the app again, You can also use location plugin instead of Geolocator, to get the user's location

Related

Geolocator position does not appear in the console

Geolocator position does not appear in the console and there is no errors also I have tried to get the longitude and latitude using position.longitude separately but nothing changes , the problem is with this line but I am not able to determine it : Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
and here is the code:
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class LoadingScreen extends StatefulWidget {
#override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
void getLocation() async{
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
onPressed: () {
getLocation();
// _determinePosition();
//Get the current location
},
child: Text('Get Location'),
),
),
);
}
}
Add following permission in AndroidManifest.xml for accessing location.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Check for service enable or not.
bool servicestatus = await Geolocator.isLocationServiceEnabled();
if(servicestatus){
print("GPS service is enabled");
}else{
print("GPS service is disabled.");
}
Now try to fetch location details.
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print(position.longitude); //Output: 80.24599079
print(position.latitude); //Output: 29.6593457

flutter could not find com.google.android.gms.vision.barcode when using flutter_barcode_scanner

I have this error when using flutter_barcode_scanner :
Local module descriptor class for com.google.android.gms.vision.barcode not found.
Error loading optional module com.google.android.gms.vision.barcode: com.google.android.gms.dynamite.DynamiteModule$LoadingException: No acceptable module found. Local version is 0 and remote version is 0.
Local module descriptor class for com.google.android.gms.vision.dynamite.barcode not found.
D/ViewRootImpl#9677bb1BarcodeCaptureActivity: ViewPostIme pointer 0
could any one help me please!
how to reproduce :
1- I just run the example provided with package
2- select scan barcode
3- the app ask for permission -> accept giving the permission
4- the scanner keep scan and did not catch the barcode
5- the error appear in android studio in the run tab
main.dart
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_barcode_scanner/flutter_barcode_scanner.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String _scanBarcode = 'Unknown';
#override
void initState() {
super.initState();
}
Future<void> startBarcodeScanStream() async {
FlutterBarcodeScanner.getBarcodeStreamReceiver(
'#ff6666', 'Cancel', true, ScanMode.BARCODE)!
.listen((barcode) => print(barcode));
}
Future<void> scanQR() async {
String barcodeScanRes;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.QR);
print(barcodeScanRes);
} on PlatformException {
barcodeScanRes = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_scanBarcode = barcodeScanRes;
});
}
// Platform messages are asynchronous, so we initialize in an async method.
Future<void> scanBarcodeNormal() async {
String barcodeScanRes;
// Platform messages may fail, so we use a try/catch PlatformException.
try {
barcodeScanRes = await FlutterBarcodeScanner.scanBarcode(
'#ff6666', 'Cancel', true, ScanMode.BARCODE);
print(barcodeScanRes);
} on PlatformException {
barcodeScanRes = 'Failed to get platform version.';
}
// If the widget was removed from the tree while the asynchronous platform
// message was in flight, we want to discard the reply rather than calling
// setState to update our non-existent appearance.
if (!mounted) return;
setState(() {
_scanBarcode = barcodeScanRes;
});
}
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Barcode scan')),
body: Builder(builder: (BuildContext context) {
return Container(
alignment: Alignment.center,
child: Flex(
direction: Axis.vertical,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () => scanBarcodeNormal(),
child: Text('Start barcode scan')),
ElevatedButton(
onPressed: () => scanQR(),
child: Text('Start QR scan')),
ElevatedButton(
onPressed: () => startBarcodeScanStream(),
child: Text('Start barcode scan stream')),
Text('Scan result : $_scanBarcode\n',
style: TextStyle(fontSize: 20))
]));
})));
}
}
Please make sure you have added these permissions in your app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<application ...>
...
</application>
I faced the same problem
Try to run on another mobile

Flutter how to get latitude, longitude using geolocator package?

Flutter how to get latitude, longitude using geolocator package?
Already gave permissions both android and ios, downloaded package using pubspec.yaml. I don't understand why can't print longitude and latitude to console? tried write print(position), print(position.longitude()), print(position.latitue()).
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class LoadingScreen extends StatefulWidget {
#override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
void getLocation() async {
print('Printing text before getCurrentLocation()');
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
print(position);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: RaisedButton(
color: Colors.red,
onPressed: () {
getLocation();
},
child: Text('Get Location'),
),
),
);
}
} ```
It should be position.latitude or position.longitude. You've used position.longitude() & position.latitude(), which is incorrect.
Also, you need to add async-await for onPressed callback. I'm assuming that you've added permissions in manifest & granted the necessary permissions as well.
Method
void getLocation() async {
Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.low);
print(position.latitude);
print(position.longitude);
}
Widget
RaisedButton(
color: Colors.red,
onPressed: () async {
await getLocation();
},
child: Text('Get Location'),
),

Flutter geolocation not showing anything

I am new to flutter and trying to create a geolocation.
however, for my following code, the screen only shows 'Loading.. Please wait..' and the map is not showing.
i am just trying to show the current location using dependencies
geolocator: ^6.1.1
Using the codes from
https://codelabs.developers.google.com/codelabs/google-maps-in-flutter#3
the Google map can be shown successfully. So it is not issues related to Google Maps Platform.
// home.dart
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
bool mapToggle = false;
var currentLocation;
GoogleMapController mapController;
#override
void initState() {
// TODO: implement initState
super.initState();
Geolocator.getCurrentPosition().then((currloc) {
setState(() {
currentLocation = currloc;
mapToggle = true;
});
});
}
void _onMapCreated(controller) {
setState(() {
mapController = controller;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home'),
),
body: Column(children: <Widget>[
Stack(
children: <Widget>[
Container(
height: MediaQuery.of(context).size.height - 80.0,
width: double.infinity,
child: mapToggle
? GoogleMap(
onMapCreated: _onMapCreated,
initialCameraPosition: CameraPosition(
target: LatLng(currentLocation.latitude,
currentLocation.longitude),
zoom: 10.0))
: Center(
child: Text(
'Loading.. Please wait..',
style: TextStyle(fontSize: 20.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;
Copy this function and call this in initState
_getCurrentLocation() async{
Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
}).catchError((e) {
print(e);
});
}
For more info checkout their pub.dev site geolocatorunder usage,make sure you setup correctly for android and ios
As #theredcap already pointed out in his comment, you most probably don't have the necessary permissions. Always read the documentation of the plugin that you are using.
I don't see:
LocationPermission permission = await Geolocator.checkPermission();
nor do I see:
LocationPermission permission = await Geolocator.requestPermission();
in your code at all, yet the plugin docs clearly explain that part. Also, in case you are new to Android in general, take a look at: https://developer.android.com/training/location/permissions

Trying to find out the current location of the device, it is showing "MissingPluginException"

I have a simple piece of code, main.dart. Any kind of help would be highly appreciated. I am using
geolocator: ^5.1.3
I am simply trying to get the location of the user. But it is showing:
MissingPluginException(No implementation found for method checkPermissionStatus on channel com.baseflow.flutter/location_permissions)
A non-null String must be provided to a Text widget.
'package:flutter/src/widgets/text.dart':
Failed assertion: line 285 pos 10: 'data != null'
I have added these lines to my AndroidManifest as well:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
My main.dart code is:
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final Geolocator geolocator = Geolocator()..forceAndroidLocationManager;
Position _currentPosition;
String _currentAddress;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Location"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
if (_currentPosition != null) Text(_currentAddress),
FlatButton(
child: Text("Get location"),
onPressed: () {
_getCurrentLocation();
},
),
],
),
),
);
}
_getCurrentLocation() {
geolocator
.getCurrentPosition(desiredAccuracy: LocationAccuracy.best)
.then((Position position) {
setState(() {
_currentPosition = position;
});
_getAddressFromLatLng();
}).catchError((e) {
print(e);
});
}
_getAddressFromLatLng() async {
try {
List<Placemark> p = await geolocator.placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = p[0];
setState(() {
_currentAddress =
"${place.locality}, ${place.postalCode}, ${place.country}";
});
} catch (e) {
print(e);
}
}
}
Is your project running on Android X? Try doing so.
Here is another helpful link: https://github.com/flutter/flutter/issues/14137
Close vscode (or android) studio and then open it and run the app.