final addresses =
await Geocoder.local.findAddressesFromCoordinates(coordinates);
selectedAddress = addresses.first;
The plugin geocoder uses a deprecated version of the Android embedding.
To avoid unexpected runtime failures, or future build failures, try to see if this plugin supports the Android V2 embedding. Otherwise, consider removing it since a future release of Flutter will remove these deprecated APIs.
If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: https://flutter.dev/go/android-plugin-migration.
Use [geolocator][1] package and write the below code to get the city name and coordinates
void main() async {
await configureInjection(Environment.dev);
WidgetsFlutterBinding.ensureInitialized();
Position _currentPosition = await getCurrentPosition();
List<Placemark> placemarks = await placemarkFromCoordinates(
_currentPosition.latitude, _currentPosition.longitude);
Placemark place = placemarks[0];
runApp(AppWidget());
}
Future<Position> getCurrentPosition() async {
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
return await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best,
);
}
Related
I have a HERE map with various functionality operating fine
I have a location indicator that currently operates Geolocator.getCurrentPosition(); which works fine, taking the lat,long and heading to place indicator.
I want it to update with users location from device.
I need to use Geolocator.getPositionStream to achieve this but after trying the implementation example online I'm stuck as it has different requirements to Current Position and the code won't work
Here is the LocationIndicator method, set to getRandom
void _addLocationIndicator(GeoCoordinates geoCoordinates, LocationIndicatorIndicatorStyle indicatorStyle) {
LocationIndicator locationIndicator = LocationIndicator();
locationIndicator.locationIndicatorStyle = indicatorStyle;
Location location = Location.withCoordinates(geoCoordinates);
location.time = DateTime.now();
location.bearingInDegrees = _getRandom(0, 360);
locationIndicator.updateLocation(location);
_hereMapController.addLifecycleListener(locationIndicator);
}
This is the given code for Stream
final LocationSettings locationSettings = LocationSettings(
accuracy: LocationAccuracy.high,
distanceFilter: 100,
);
StreamSubscription<Position> positionStream = Geolocator.getPositionStream(locationSettings: locationSettings).listen(
(Position position) {
print(position == null ? 'Unknown' : position.latitude.toString() + ', ' + position.longitude.toString());
});
This is the Current Location example which I have used and it works fine for current location
import 'package:geolocator/geolocator.dart';
/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> _determinePosition() async {
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled don't continue
// accessing the position and request users of the
// App to enable the location services.
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
// When we reach here, permissions are granted and we can
// continue accessing the position of the device.
return await Geolocator.getCurrentPosition();
}
Thanks
I'm trying to get the location of my phone with geolocation however the variable that stores location when you a press the button to get location has to be store as null at the beginning as I do not have the location of the phone yet however when I do that I get an error 'Non-nullable instance field 'currentposition' must be initialized' how to I fix this
this is my code
class _HomeState extends State<Home> {
String currentAddress = 'My Address';
Position currentposition;
void initState() {}
Future<Position> _determinePosition() async {
bool serviceEnabled; //check location service is enabled
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
Fluttertoast.showToast(msg: 'Please enable Your Location Service');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
Fluttertoast.showToast(msg: 'Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
Fluttertoast.showToast(
msg:
'Location permissions are permanently denied, we cannot request permissions.');
}
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
try {
List<Placemark> placemarks =
await placemarkFromCoordinates(position.latitude, position.longitude);
Placemark place = placemarks[0];
setState(() {
currentposition = position;
currentAddress =
"${place.locality}, ${place.postalCode}, ${place.country}";
print(currentposition);
});
} catch (e) {
print(e);
}
throw "";
}
If you declare a variable then you also have to initialize it by passing some value to it. But in any case you want to assign value later then you can define it as late making this change to your variable you can also make it nullable by using ?
late Position currentposition; //late initialize but not null
and nullable with late
late Position? currentposition; //late initialize nullable
How can I request permission for accessing the device microphone for recording audio in Flutter?
I have tried looking this up but haven't been able to find a clear answer.
You could do something like this:
await _askingPermission();
Future<String> _askingPermission() async {
final PermissionStatus permissionStatus =
await _getPhonePermission();
if (permissionStatus == PermissionStatus.granted){
//permission is granted
} else{
//permission denied or undermined
}
}
Future<PermissionStatus> _getPermission() async {
final PermissionStatus permission = await Permission.microphone.status;
if (permission != PermissionStatus.granted &&
permission != PermissionStatus.denied) {
final Map<Permission, PermissionStatus> permissionStatus =
await [Permission.microphone].request();
return permissionStatus[Permission.microphone] ??
PermissionStatus.undetermined;
} else {
return permission;
}
}
Add this line in your manifest file
<uses-permission android:name="android.permission.RECORD_AUDIO" />
I'm using a location plugin to get the current location of the device. However, on certain devices, await getLocation() never returns (there are also no errors in the debug console). How do I handle such an issue?
this is my code for getCurrentLocation()
import 'package:geolocator/geolocator.dart';
import 'location.dart';
/// Determine the current position of the device.
///
/// When the location services are not enabled or permissions
/// are denied the `Future` will return an error.
Future<Position> getCurrentLocation() async {
bool serviceEnabled;
LocationPermission permission;
Position position;
await reqLocation(); // requests turn on location
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.deniedForever) {
return Future.error(
'Location permissions are permantly denied, we cannot request permissions.');
}
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission != LocationPermission.whileInUse &&
permission != LocationPermission.always) {
return Future.error(
'Location permissions are denied (actual value: $permission).');
}
}
print('LOGIC');
position = await Geolocator.getCurrentPosition();
if (position == null) {
print('null');
} else {
print('LOCATION');
print(position);
}
return position;
}
Use a timeout for your future to handle this case: Flutter - Future Timeout
Use your future like this:
var result = await getCurrentLocation().timeout(const Duration(seconds: 5, onTimeout: () => null));
Now, your future runs for 5 seconds and if the operation is not complete yet, the future completes with null (because onTimeout returned null. You can use a different value as you like [Refer to the link above]).
Now check result. if null, the operation did not complete within specified time limit else you get your position value in result as usual if it managed to complete within the specified duration.
Trying to write a permission code for camera, microphone and map on flutter
Here is the code, Please what is wrong with this code
its in a dart file which would accessible
class Permissions {
static Future<bool> cameraAndMicrophonePermissionsGranted() async {
PermissionStatus cameraPermissionStatus = await _getCameraPermission();
PermissionStatus microphonePermissionStatus =
await _getMicrophonePermission();
if (cameraPermissionStatus == PermissionStatus.granted &&
microphonePermissionStatus == PermissionStatus.granted) {
return true;
} else {
_handleInvalidPermissions(
cameraPermissionStatus, microphonePermissionStatus);
return false;
}
}
static Future<PermissionStatus> _getCameraPermission() async {
PermissionStatus permission =
await PermissionHandler().checkPermissionStatus(PermissionGroup.camera);
if (permission != PermissionStatus.granted &&
permission != PermissionStatus.disabled) {
Map<PermissionGroup, PermissionStatus> permissionStatus =
await PermissionHandler()
.requestPermissions([PermissionGroup.camera]);
return permissionStatus[PermissionGroup.camera] ??
PermissionStatus.unknown;
} else {
return permission;
}
}
static Future<PermissionStatus> _getMicrophonePermission() async {
PermissionStatus permission = await PermissionHandler()
.checkPermissionStatus(PermissionGroup.microphone);
if (permission != PermissionStatus.granted &&
permission != PermissionStatus.disabled) {
Map<PermissionGroup, PermissionStatus> permissionStatus =
await PermissionHandler()
.requestPermissions([PermissionGroup.microphone]);
return permissionStatus[PermissionGroup.microphone] ??
PermissionStatus.unknown;
} else {
return permission;
}
}
static void _handleInvalidPermissions(
PermissionStatus cameraPermissionStatus,
PermissionStatus microphonePermissionStatus,
) {
if (cameraPermissionStatus == PermissionStatus.denied &&
microphonePermissionStatus == PermissionStatus.denied) {
throw new PlatformException(
code: "PERMISSION_DENIED",
message: "Access to camera and microphone denied",
details: null);
} else if (cameraPermissionStatus == PermissionStatus.disabled &&
microphonePermissionStatus == PermissionStatus.disabled) {
throw new PlatformException(
code: "PERMISSION_DISABLED",
message: "Location data is not available on device",
details: null);
}
}
}
the errors are
method "PermissionHandler" is not defined in the class "Permissions"
Undefined name "PermissionGroup"
the getter 'disable' is not defined in the class PermissionStatus
the name "PermissionGroup" isn't a type so it cant be used as a type argument
Undefined name "disabled"
what can be wrong with this code?
Since Version
permission_handler 5.0.0
new methods of checking and requesting permissions are as follows
Old : await PermissionHandler() .checkPermissionStatus(PermissionGroup.camera)
New : await Permission.camera.status
Old : (await PermissionHandler() .requestPermissions([PermissionGroup.camera]))[PermissionGroup.camera]
New : await Permission.camera.request()
Old : await PermissionHandler() .requestPermissions([PermissionGroup.camera, PermissionGroup.storage]))
New : await [Permission.camera, PermissionGroup.storage].request()
Old : await PermissionHandler() .checkServiceStatus(PermissionGroup.location)
New : await Permission.location.serviceStatus.isEnabled
Your code use permission_handler 3.3.0
In pubspec.yaml , you must specify version 3.3.0
dependencies:
flutter:
sdk: flutter
permission_handler: 3.3.0