如果语句已在我的Dart Flutter代码中注册为变量?我该如何更改?

问题描述 投票:0回答:2

The highlighted text is giving me errors like those shown in my Problems console. I've never receieved these kinds of issues when dealing with if statements, and I'm wondering why they are no registering as if statements. In one of the errors it says "if is already defined", but its not a variable. How do I solve this? Does it have anything to do with the async functions? I struggled with these.

图像中突出显示的文本给我类似我的问题控制台中显示的错误。在处理if语句时,我从来没有收到过这类问题,我想知道为什么它们没有像if语句那样注册。在其中一个错误中,它说“是否已定义”,但不是变量。我该如何解决?它与异步功能有关系吗?我为此感到挣扎

[我正在尝试为计划在Flutter App中实现的地图请求用户位置数据,但是它不起作用:/如果无法解决,我的if出现了问题。

Future<bool> assignService(Location loc) async {
  bool servicestatus = await loc.serviceEnabled();
  return servicestatus;
}

Future<PermissionStatus> assignPermission(Location loc) async {
  return await loc.hasPermission();
}

Future<LocationData> assignLocation(Location loc) async {
  return await loc.getLocation();
}

Location location = new Location();

var _serviceEnabled = assignService(location);

if (_serviceEnabled != true) {
  _serviceEnabled = assignService(location);
  if (!_serviceEnabled) {
    return;
  }
}

var _permissionGranted = assignPermission(location);

if (_permissionGranted == PermissionStatus.denied) async{
  _permissionGranted = await location.requestPermission();
  if (_permissionGranted != PermissionStatus.granted) {
    return;
  }
}

var _locationData = assignLocation(location);

更新(上述代码之前的代码):

  Future<bool> assignService(Location loc) async {
  bool servicestatus = await loc.serviceEnabled();
  return servicestatus;
}

Future<PermissionStatus> assignPermission(Location loc) async {
  return await loc.hasPermission();
}

Future<LocationData> assignLocation(Location loc) async {
  return await loc.getLocation();
}

Location location = Location();

var _serviceEnabled = assignService(location);

var _permissionGranted = assignPermission(location);
flutter dart geolocation dart-pub flutter-test
2个回答
1
投票

您在函数外部编写了代码。仅变量声明可以在函数外部,而不能在代码外部。

例如,您可以做:

  void StartService() {
    if (_serviceEnabled != true) {
      _serviceEnabled = assignService(location);
      if (!_serviceEnabled) {
        return;
      }

    if (_permissionGranted == PermissionStatus.denied) async{
      _permissionGranted = await location.requestPermission();
      if (_permissionGranted != PermissionStatus.granted) {
        return;
      }
    }
  }

如果不应该在代码块之外。您必须将其放入函数中。这说明了您的错误。

如果需要更多详细信息,请告诉我。

编辑:仅用于提供信息,不再需要“ new”关键字。


1
投票

解决方案非常简单,if不能成为您应该在函数内进行if检查的类的成员。

void doIfChecks(){
// if statements
}

希望这会对您有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.