简体   繁体   English

Flutter 如何使用函数的异步返回值

[英]Flutter how to use async return value from a function

I'm new to flutter, I just want to ensure if the below code is correct, I want to check if the location permission was granted or no, if yes then get the current location and save into shared preferences and THEN go to the homepage route, otherwise go to the location page to ask the user for access his location我是新手,我只想确保以下代码是否正确,我想检查是否授予了位置权限,如果是,则获取当前位置并保存到共享首选项中,然后转到主页路线,否则转到位置页面要求用户访问他的位置

@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;
    }
  }

As mentioned in this Stack Overflow answer , the following changes should sufficient正如此Stack Overflow 答案中所述,以下更改应该足够了

@override
void initState() {
  super.initState();
  WidgetsBinding.instance.addPostFrameCallback((_) => checkLocation(context));
}

Though I would like to point out that context is not available in initState (unless it's a variable that you've created and are managing)虽然我想指出contextinitState不可用(除非它是您创建并管理的变量)

All the functions defined are correct and the methodology is also fine.定义的所有功能都是正确的,方法也很好。 It should work with no issues.它应该可以正常工作。 However I would suggest instead of defining all the functions here in the widget class you should separate it out from the UI by creating a separate class (Example: LocationService) and then initialize that class here and then make use of the functions.但是,我建议不要在小部件类中定义所有函数,您应该通过创建一个单独的类(例如:LocationService)将其与 UI 分开,然后在此处初始化该类,然后使用这些函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM