我是新手,我只是想确保下面的代码是否正确,我想检查位置权限是否被授予,如果是,那么获取当前位置并保存到共享首选项中,然后转到主页路由,否则转到位置页面要求用户访问他的位置
@override
void initState() {
super.initState();
checkLocation(context);
}
void checkLocation(context) async {
bool isGranted = await asyncFunction();
if(isGranted)
{
updateSettingLocation();
Navigator.of(context).pushNamed('/homepage');
} else{
Navigator.of(context).pushNamed('/location');
}
}
void updateSettingLocation() async{
final location = await currentLocation();
settingsRepo.setCurrentLocation(location);
}
Future<Position> currentLocation() {
return Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
.then((location) {
if (location != null) {
print("Location: ${location.latitude},${location.longitude}");
}
return location;
});
}
void updateCurrentLocation() async {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
settingsRepo.setCurrentLocation(position);
}
Future<bool> asyncFunction() async {
bool serviceEnabled;
LocationPermission permission;
permission = await Geolocator.checkPermission();
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (permission == LocationPermission.denied || !serviceEnabled || permission == LocationPermission.deniedForever) {
print('location access is denied');
return false;
} else {
print('location access is granted');
return true;
}
}
正如在这个Stack Overflow答案中提到的,以下更改应该足够
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => checkLocation(context));
}
虽然我想指出context
在initState
中不可用(除非它是您创建并正在管理的变量)
定义的所有函数都是正确的,方法也很好。应该没有问题。然而,我建议不要在小部件类中定义所有的函数,你应该通过创建一个单独的类(例如:LocationService)将它从UI中分离出来,然后在这里初始化该类,然后使用这些函数。