Problem in storing LocationData in flutter - flutter

I am trying getting the location coordinates of user and storing it in variable.
I use the location library from flutter.
But I get this error:
type 'Future' is not a subtype of type 'Future'
This is my code
Future<LocationData> coords;
double lat, long;
coords = getUserLocationCoordinates();
coords.then((value) => {
lat = value.latitude,
long = value.longitude,
});
My getUserLocationCoordinates function
getUserLocationCoordinates() async {
LocationData currentLocation;
String error;
Location location = Location();
try {
currentLocation = await location.getLocation();
} on PlatformException catch (e) {
if (e.code == 'PERMISSION_DENIED') {
error = 'please grant permission';
print(error);
}
if (e.code == 'PERMISSION_DENIED_NEVER_ASK') {
error = 'permission denied- please enable it from app settings';
print(error);
}
currentLocation = null;
}
return currentLocation;
}
Any help is greatly appreciated

Initialize variables
String latitude_data;
String longitude_data;
bool _serviceEnabled;
Current Location Function
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 {
///Do something here
}
LocationData _currentPosition = await location.getLocation();
longitude_data=_currentPosition.longitude.toString();
latitude_data=_currentPosition.latitude.toString();
///if you want you can save data to sharedPrefrence
SharedPrefrence().setLatitude(_currentPosition.latitude.toString());
SharedPrefrence().setLongitude(_currentPosition.longitude.toString());
}

Related

Stream<Position> of Geolocator.getPositionStream is not listen

I'm using geolocator and google_maps_flutter in my app to get user location, passing by getPositionStream.
The Map is the first screen of the app, and when I get user location it work fine, and the camera of the map zoom correctly.
But the user can login to his account, and it's recreated the Map. And my problem is here. When the login is done, my stream with my new location is not listen :/ I need to reload the app for that
My function in my viewModel
final Stream<Position>? stream = await _locationService.getLocation();
if (stream != null) {
stream.listen((location) async {
final newLocation =
CameraPosition(target: LatLng(location.latitude, location.longitude), zoom: 15);
if (controllerCompleter != null) {
final GoogleMapController controller = await controllerCompleter.future;
controller.animateCamera(CameraUpdate.newCameraPosition(newLocation));
}
});
}
In the locationService:
Future<Stream<Position>?> getLocation() async {
bool _serviceEnabled;
LocationPermission _permissionGranted;
_serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!_serviceEnabled) {
return null; // Use France's GPS coordinates by default
}
_permissionGranted = await Geolocator.checkPermission();
if (_permissionGranted == LocationPermission.denied) {
_permissionGranted = await Geolocator.requestPermission();
if (_permissionGranted == LocationPermission.denied ||
_permissionGranted == LocationPermission.deniedForever) {
return null; // Use France's GPS coordinates by default
} else {
return Geolocator.getPositionStream(locationSettings: locationSettings);
}
} else {
return Geolocator.getPositionStream(locationSettings: locationSettings);
}
}
If anyone have an idea of what I'm doing wrong.
Thanks in advance

Want to post geolocation on a external api using getx

I have already got the geolocation with longitude and latitude using the geolocation plugin with getx but now I want to post the same longitude and latitude on API with already present in the backhand the model is yet to be created and even the provider is also yet to be done and I don't know how and the location API post should run in the background once with the application opens up.
API body:-
{
"longitude":"55.5852",
"latitude":"77.6532"
}
Controller code:-
class RootController extends GetxController {
var latitude = 'Getting Latitude..'.obs;
var longitude = 'Getting Longitude..'.obs;
var address = 'Getting Address..'.obs;
final currentIndex = 0.obs;
final notificationsCount = 0.obs;
final customPages = <CustomPage>[].obs;
NotificationRepository _notificationRepository;
CustomPageRepository _customPageRepository;
StreamSubscription<Position> streamSubscription;
RootController() {
_notificationRepository = new NotificationRepository();
_customPageRepository = new CustomPageRepository();
}
#override
void onInit() async {
await getCustomPages();
getNotificationsCount();
if (Get.arguments != null && Get.arguments is int) {
changePageInRoot(Get.arguments as int);
} else {
changePageInRoot(0);
}
super.onInit();
getLocation();
}
#override
void onReady(){
super.onReady();
}
#override
void onClose(){
streamSubscription.cancel();
}
getLocation() async{
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if(!serviceEnabled){
await Geolocator.openLocationSettings();
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){
return Future.error('Location permissions are permanently denied');
}
streamSubscription = Geolocator.getPositionStream().listen((Position position) {
latitude.value = 'Latitude:${position.latitude}';
longitude.value = 'Longitude:${position.latitude}';
getAddressFromLatLang(position);
print(latitude.value);
print(longitude.value);
});
}
Future<void> getAddressFromLatLang(Position position)async{
List<Placemark> placemark = await
placemarkFromCoordinates(position.latitude,position.longitude);
Placemark place = placemark[0];
address.value = 'address:${place.locality},${place.country}';
}
List<Widget> pages = [
HomeView(),
// EServicesView2(),
ReviewsView(),
MessagesView(),
AccountView(),
];
Widget get currentPage => pages[currentIndex.value];
/**
* change page in route
* */
void changePageInRoot(int _index) {
currentIndex.value = _index;
}
void changePageOutRoot(int _index) {
currentIndex.value = _index;
Get.offNamedUntil(Routes.ROOT, (Route route) {
if (route.settings.name == Routes.ROOT) {
return true;
}
return false;
}, arguments: _index);
}
Future<void> changePage(int _index) async {
if (Get.currentRoute == Routes.ROOT) {
changePageInRoot(_index);
} else {
changePageOutRoot(_index);
}
await refreshPage(_index);
}
Future<void> refreshPage(int _index) async {
switch (_index) {
case 0:
{
await Get.find<HomeController>().refreshHome();
break;
}
case 2:
{
await Get.find<MessagesController>().refreshMessages();
break;
}
}
}
void getNotificationsCount() async {
notificationsCount.value = await _notificationRepository.getCount();
}
Future<void> getCustomPages() async {
customPages.assignAll(await _customPageRepository.all());
}
}
what else should I do?

Functions by file extension in Flutter

I’m using image picker package.
“https://pub.dev/packages/image_picker”
// Get from gallery
void ImgFromGallery() async {
final pickedFile = await picker.pickImage(source: ImageSource.gallery);
setState(() {
if (pickedFile != null) {
_proImage = File(pickedFile.path);
List<int> imageBytes = _proImage!.readAsBytesSync();
image = base64Encode(imageBytes);
print("_Proimage:$_proImage");
} else {
print('No image selected.');
}
});
}
It works, but if the user chooses a .gif format from his gallery, I want to run a different function. Can i check extension for selected file? If yes how can i do that? I’m new on Flutter.
File? _file;
String _imagePath = "";
bool imageAccepted;
takeImageFromGallery() async {
XFile? image = await ImagePicker().pickImage(source: ImageSource.gallery);
if (image!.path.endsWith("png")) {
imageAccepted = true;
} else if (image.path.endsWith("jpg")) {
imageAccepted = true;
} else if (image.path.endsWith("jpeg")) {
imageAccepted = true;
} else {
imageAccepted = false;
}
if (imageAccepted) {
if (image != null) {
setState(() {
_imagePath = image.path;
_file = File(_imagePath);
});
}
} else {
SnackBar(content: Text("This file extension is not allowed"));
}
}
You can use Path package like this:
import 'package:path/path.dart' as p;
final path = '/some/path/to/file/file.dart';
final extension = p.extension(path); // '.dart'

How to get Fips code of county from geolocator and geocode in flutter?

The below code gets the coordinates and the location. But I don't know how to get county fips
code from this.
Future<void> getUserLocation() async {
currentPosition = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
try {
List<Placemark> placemarks = await placemarkFromCoordinates(
currentPosition.latitude, currentPosition.longitude);
place = placemarks[0];
} catch (e) {
print(e);
}
}

Live location in flutter

How to get the coordinates of live location in flutter ? I want to get the live location coordinates. What could be done to get this ? I am imported the location package in flutter but I just want to get the coordinates of live location .
First of all you need to get a location plugin.
https://pub.dev/packages/location. Also I recommend that use Provider plugin and create model files. It will be more easier to manage. In addition , you have to check permission status of your device . you will reach all of information what you want to learn through link
class MyHomePage extends StatefulWidget {
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Location _location = Location();
LocationData currentLocation;
#override
void initState() {
location = new Location();
location.onLocationChanged.listen((LocationData cLoc) {
currentLocation = cLoc;
});
super.initState();
}
#override
Widget build(BuildContext context) {
return Center(
child: Text(
'Location: Lat${currentLocation.latitude}, Long: ${currentLocation.longitude}'),);}}
Location location = new Location();
bool _serviceEnabled;
PermissionStatus _permissionGranted;
LocationData _locationData;
_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return;
}
}
_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}
location.onLocationChanged.listen((LocationData currentLocation) {
// Use current location
});