【问题标题】:NoSuchMethodError the method was called on NullNoSuchMethodError 该方法在 Null 上被调用
【发布时间】:2019-12-26 15:29:02
【问题描述】:

在 WeatherModel 下面的这段代码中,试图获取 android 手机的当前位置, 我的问题是一旦我开始运行它就会显示 NoSuchMethod Found,它说接收者为空, 因为我尝试了很多调试只是为了看看我的问题在哪里。 我现在明白我的问题是当我在 WeatherModel 中创建 Location() 实例时,经度和纬度为空,它永远不会获得价值,我不知道为什么......

对不起我的英语不好:(

const apiKey = 'e3653190f2b1d4803287b3074ecfe618';
const apiWeatherURL = 'https://api.openweathermap.org/data/2.5/weather';

class WeatherModel {

  Future<dynamic> getLocationWeather() async {

    Location location = Location();

    NetworkHelper networkHelper = NetworkHelper(
        'https://api.openweathermap.org/data/2.5/weather?lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey');
    var weatherData = networkHelper.getData();
    return weatherData;
  }

  }
.....

class Location {
  double latitude;
  double longitude;

  Future<void> getCurrentLocation() async {
    try {
      Position _position = await Geolocator()
          .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
      longitude = _position.longitude;
      print(longitude);
      latitude = _position.latitude;
      print(latitude);
    } catch (e) {
      print(e);
    }
  }
}
.........

class NetworkHelper {
  NetworkHelper(this.url);
  final url;

  Future getData() async {
    http.Response response = await http.get(url);
    if (response.statusCode == 200) {
      var data = jsonDecode(response.body);
      print(" Sarkawtua $data");
      return data;
    } else
      print("Error ${response.statusCode} keshay Internet");
  }
}

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    因为你的实例字段没有更新,所以它们是空的。您有获取当前位置的方法,但它没有在 getLocationWeather 中触发。

    Future<dynamic> getLocationWeather() async {
    
        Location location = Location();
        await location.getCurrentLocation();
    
        NetworkHelper networkHelper = NetworkHelper(
            'https://api.openweathermap.org/data/2.5/weather?lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey');
        var weatherData = await networkHelper.getData();
        return weatherData;
      }
    

    编辑:您还必须等待networkHelper.getData() 方法才能获得非未来对象。

    【讨论】:

      猜你喜欢
      • 2020-07-13
      • 2021-10-25
      • 2020-10-12
      • 2019-02-07
      • 2020-04-09
      • 2020-09-25
      • 2020-06-07
      • 1970-01-01
      • 2022-11-07
      相关资源
      最近更新 更多