You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Dart Flutter报错:Instance member can't be accessed using static access定位求助

解决Dart/Flutter报错:Instance member can't be accessed using static access

问题原因

你调用WeatherModel.getLocationWeather()时用了类名直接调用的静态访问方式,但getLocationWeather()是WeatherModel的实例方法,Dart要求实例方法必须通过类的实例对象调用,不能直接用类名访问。

解决方案(二选一)

方案1:创建类实例后调用方法(推荐)

修改调用getLocationWeather()的代码,先创建WeatherModel的实例,再通过实例调用方法:

void getLocationData() async {
  // 创建WeatherModel实例
  WeatherModel weatherModel = WeatherModel();
  var weatherData = await weatherModel.getLocationWeather();

  Navigator.push(context, MaterialPageRoute(builder: (context) {
    return LocationScreen(
      locationWeather: weatherData,
    );
  }));
}

方案2:将方法改为静态方法

如果这个方法不需要依赖WeatherModel的实例变量,可以把getLocationWeather()改成静态方法,这样就能用类名直接调用:
修改WeatherModel中的方法:

class WeatherModel {
  // ...其他代码保持不变

  // 添加static关键字,将方法改为静态方法
  static Future<dynamic> getLocationWeather() async {
    Location location = Location();
    await location.getCurrentLocation();

    NetworkHelper networkHelper = NetworkHelper(
        '$openWeatherMapURL?lat=${location.latitude}&lon=${location.longitude}&appid=$apiKey&units=metric');

    var weatherData = await networkHelper.getData();
    return weatherData;
  }
}

修改后,原来的WeatherModel.getLocationWeather()调用可以正常使用。

内容的提问来源于stack exchange,提问作者user22030129

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 23:41:04