flutter-web: get location on web by Location plugin - flutter

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,
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.

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

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

Related

Track user location globally in flutter (at background too)

I need to track user location at background in every screen of my app, i already implemented a method to take location with geolocator package, but it only works if i put the code in every app screen. Is it possible in flutter?
ps.: i tried to use workmanager, but the minimum interval is 15 minutes, and i need to receive the location in an interval of 3 seconds.
my actually code bellow:
getPosicaoAtual() async {
try {
Position posicao = await _posicaoAtual();
DbUtil.insert('local', {
'latitude': posicao.latitude,
'longitude': posicao.longitude,
});
_local = {
'latitude': posicao.latitude,
'longitude': posicao.longitude,
};
} catch (e) {
clearLocal();
_local['erro'] = e.toString();
}
notifyListeners();
}
Future<Position> _posicaoAtual() async {
LocationPermission permissao;
// Location location = new Location();
bool ativado = await Geolocator.isLocationServiceEnabled();
if (!ativado) {
// await location.requestService();
if (!await Geolocator.isLocationServiceEnabled()) {
return Future.error('Por favor, habilite a localização no smartphone');
}
}
permissao = await Geolocator.checkPermission();
if (permissao == LocationPermission.denied) {
permissao = await Geolocator.requestPermission();
if (permissao == LocationPermission.denied) {
return Future.error('Você precisa autorizar o acesso à localização');
}
}
if (permissao == LocationPermission.deniedForever) {
return Future.error('-1');
}
return await Geolocator.getCurrentPosition();
}
You should use https://pub.dev/packages/flutter_background_service
To run flutter code in background even app is terminated

Flutter Error: Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord

I needed to import contacts from mobile, and I used contacts_service from pub.dev. Then I made the changes required in AndroidManifest.xml for android and in info.plist for iOS, i.e, added the required permission, still I am getting this error when I am trying to read contacts from phone.
Permission Denial: opening provider com.android.providers.contacts.ContactsProvider2 from ProcessRecord
I resolved this issue, by requesting permission from the user, like this,
#override
void initState() {
super.initState();
getContacts();
}
// Function to get permission from the user
_contactsPermissions() async {
PermissionStatus permission = await Permission.contacts.status;
if (permission != PermissionStatus.granted && permission != PermissionStatus.denied) {
Map<Permission, PermissionStatus> permissionStatus = await [Permission.contacts].request();
return permissionStatus[Permission.contacts] ?? PermissionStatus.undetermined;
} else {
return permission;
}
}
//Function to import contacts
getContacts() async {
PermissionStatus contactsPermissionsStatus = await _contactsPermissions();
if (contactsPermissionsStatus == PermissionStatus.granted) {
List<Contact> _contacts = (await ContactsService.getContacts(withThumbnails: false)).toList();
setState(() {
contacts = _contacts;
});
}
}

If statement is being registered as a variable in my Dart Flutter code? How do I change this?

The highlighted text in the image is giving me errors like those shown in my Problems console. I've never receieved these kinds of issues when dealing with if statements, and I'm wondering why they are no registering as if statements. In one of the errors it says "if is already defined", but its not a variable. How do I solve this? Does it have anything to do with the async functions? I struggled with these
I am trying to request the user location data for a map I plan to implement in a flutter App, but it's not working :/ SOMETHING is wrong with my ifs that I can't solve.
Future<bool> assignService(Location loc) async {
bool servicestatus = await loc.serviceEnabled();
return servicestatus;
}
Future<PermissionStatus> assignPermission(Location loc) async {
return await loc.hasPermission();
}
Future<LocationData> assignLocation(Location loc) async {
return await loc.getLocation();
}
Location location = new Location();
var _serviceEnabled = assignService(location);
if (_serviceEnabled != true) {
_serviceEnabled = assignService(location);
if (!_serviceEnabled) {
return;
}
}
var _permissionGranted = assignPermission(location);
if (_permissionGranted == PermissionStatus.denied) async{
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
var _locationData = assignLocation(location);
Update (code before that above):
Future<bool> assignService(Location loc) async {
bool servicestatus = await loc.serviceEnabled();
return servicestatus;
}
Future<PermissionStatus> assignPermission(Location loc) async {
return await loc.hasPermission();
}
Future<LocationData> assignLocation(Location loc) async {
return await loc.getLocation();
}
Location location = Location();
var _serviceEnabled = assignService(location);
var _permissionGranted = assignPermission(location);
You wrote code outside a function.
Only variable declaration can be outside a function, not code.
For example you can do :
void StartService() {
if (_serviceEnabled != true) {
_serviceEnabled = assignService(location);
if (!_serviceEnabled) {
return;
}
if (_permissionGranted == PermissionStatus.denied) async{
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
}
The if shouldn't be outside code block.
You have to put it in a function. That's explain your error.
Tell me if you need more details.
Edit : just for information, the "new" keyword is not needed in flutter anymore.
Solution is very simple if can't be the member of a class you should do if checks inside a function.
void doIfChecks(){
// if statements
}
Hope this will help you.

Flutter Location package requestService() never returns

I have a function like this. Using Location package from flutter it shows the dialog to enable GPS.
Future<bool> _checkServiceStatus() async {
final Location location = Location();
bool serviceStatus = await location.serviceEnabled();
if (!serviceStatus) {
serviceStatus = await location.requestService();
print('status -> $serviceStatus');
}
return serviceStatus;
}
When its calling await location.requestService(), it is showing the dialog to enable GPS but after that it never returns the result.
Even its not executing the print() function.
What am i doing wrong here?
Any help would be very appreciated! Thanks in advance.
I had the same issue. It could be solved by upgrading your Flutter project, follow this link https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects
Try this code to check wather permission enabled, service enabled than it returns true else false. Must configure "location" package related configuration in android and ios projects.
Future<bool> checkServiceStatus() async {
final Location location = Location();
final locationPermission = await location.hasPermission();
if (locationPermission == PermissionStatus.granted) {
final locationServiceEnabled = await location.serviceEnabled();
if (locationServiceEnabled == true) {
return true;
} else {
final requestServiceStatus = await location.requestService();
if (requestServiceStatus == true) {
return true;
} else {
BotToast.showSimpleNotification(
title: "Enable GPS to allow this feature");
return false;
}
}
} else {
BotToast.showSimpleNotification(title: "Required location permission to allow this feature");
return false;
}
}

GPS off message, and continous location update flutter

i made an app which uses the geolocator package to check for GPS and get the location of the user, and i use the provider package to handle the state. The problem is, when the GPS is switched off, a red screen appears that says the latitude was null, i would like to implement a screen to tell the user to switch on the GPS, and update the location accordingly.
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:geolocator/geolocator.dart';
import 'package:latlong/latlong.dart';
class MapState with ChangeNotifier {
bool locationServiceActive = true;
MapController _mapController;
MapController get mapController => _mapController;
static var _initialPosition;
var _lastPosition = _initialPosition;
LatLng get initialPosition => _initialPosition;
LatLng get lastPosition => _lastPosition;
MapState(){
checkGPS();
_getUserLocation();
}
checkGPS() async{
bool conn = await Geolocator().isLocationServiceEnabled();
if(conn == false){
locationServiceActive = false;
} else {
locationServiceActive = true;
}
notifyListeners();
}
void _getUserLocation() async{
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
print("/////////////////////////////////////////////////////////////////////////////////position");
print(position);
_initialPosition = LatLng(position.latitude, position.longitude);
notifyListeners();
}
}
update:-
i changed my _getUserLocation function to a stream, which works much better if the user switched on or off the gps (and it uses the last known location if the gps is off)... but it doesn't print the statement in the terminal if the position is null which is weird, only when there is lat and lng!!!
here is the modification i made...
void _getUserLocation() async{
Position position = await Geolocator().getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
var geolocator = Geolocator();
var locationOptions = LocationOptions(accuracy: LocationAccuracy.high, distanceFilter: 10);
StreamSubscription<Position> positionStream = geolocator.getPositionStream(locationOptions).listen(
(Position position) {
print("/////////////////////////////////////////////////////////////////////////// position");
print(position == null ? 'Unknown' : position.latitude.toString() + ', ' + position.longitude.toString());
});
_initialPosition = LatLng(position.latitude, position.longitude);
notifyListeners();
}
If you want to notify the user about the GPS, you can use something like this
#override
void initState() {
super.initState();
initPlatformState();
location.onLocationChanged.listen((result) {
currentLocation = result;
// your code
});
});
}
void initPlatformState() async {
LocationData currentLocation;
try {
currentLocation = await location.getLocation();
error = "";
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED')
error = 'Permission Denied';
else if (e.code == 'PERMISSION_DENIED_NEVER_ASK')
error =
'Permission denied - please ask the user to enable it from the app settings';
currentLocation = null;
}
setState(() {
currentLocation = currentLocation;
});
}
Here, you are listening to the location stream if enabled. In case it is not then it throws an error. The package being used here is location