[英]How to fix Non-nullable instance when trying to get phones location
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我正在尝试通过地理位置获取手机的位置,但是当您按下按钮获取位置时存储位置的变量必须在开始时存储为 null,因为我还没有手机的位置但是当我这样做我得到一个错误'不可为空的实例字段'当前位置'必须被初始化'我如何解决这个问题
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.如果您声明一个variable
,那么您还必须通过向它传递一些value
来initialize
它。 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 ?
但是在任何情况下,您想later
分配值,然后您可以将其define
为late
对您的变量进行此更改,您也nullable
使用?
late Position currentposition; //late initialize but not null
and nullable with late并且迟到时可以为空
late Position? currentposition; //late initialize nullable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.