我是新手,我只想確保以下代碼是否正確,我想檢查是否授予了位置權限,如果是,則獲取當前位置并保存到共享首選項中,然后轉到主頁路線,否則轉到位置頁面要求用戶訪問他的位置
@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;
}
}
uj5u.com熱心網友回復:
正如此Stack Overflow 答案中所述,以下更改應該足夠了
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) => checkLocation(context));
}
雖然我想指出它context不可用initState(除非它是您創建并管理的變數)
uj5u.com熱心網友回復:
定義的所有功能都是正確的,方法也很好。它應該可以正常作業。但是,我建議不要在小部件類中定義所有函式,您應該通過創建一個單獨的類(例如:LocationService)將其與 UI 分開,然后在此處初始化該類,然后使用這些函式。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/335008.html
