I’m new to learning flutter and am learning about the flutter location package.I have declared a function that can be called on the press of a button. The function has to print latitude and longitude to the console. Can you tell me where I went wrong as nothing is getting printed on the console.
Code:
class LoadingScreen extends StatefulWidget {
const LoadingScreen({super.key});
@override
State<LoadingScreen> createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
void getLocation() async {
Location location = 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;
}
}
locationData = await location.getLocation();
print("${locationData.latitude}, ${locationData.longitude}");
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: getLocation,
child: const Text('Get Location'),
),
),
);
}
}
I have granted the permission ‘always allow when using this app’.
location version: 4.2.0
3
Answers
If your are runing your app on Android device you should add
< uses-permission android:name = "android.permission.ACCESS_FINE_LOCATION" />
to your android/app/src/main/AndroidManifest.xml file
To debug, you can include a print statement before the return statement to see if the function returns one of two cases.
Example:
tested your code, and works fine.
after you install the package Location, remember that you have to add for ios in info.plist:
and on android, in manifest.xml:
finally, remember that you have to restart the app