dart 我无法找到修复此错误的位置,该错误指出“无法使用静态访问访问示例成员”

b5lpy0ml  于 2023-07-31  发布在  其他
关注(0)|答案(2)|浏览(99)

我得到这个错误
无法使用静态访问访问示例成员
我不能定位在哪里,因为我有数据相关的错误在另一个类。我是新的 dart Flutter和仍在学习,所以这一切都是没有意义的我很多。
代码在哪里我得到这个错误是在.getLocationWeather()

void getLocationData() async {
    var weatherData = await WeatherModel.getLocationWeather();

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

字符串
下面是getLlocationWeather()所在的类代码。

import 'location.dart';
import 'networking.dart';

const apiKey = 'e72ca729af228beabd5d20e3b7749713';
const openWeatherMapURL = 'https://api.openweathermap.org/data/2.5/weather';

class WeatherModel {
  Future<dynamic> getCityWeather(String cityName) async {
    NetworkHelper networkHelper = NetworkHelper(
        '$openWeatherMapURL?q=$cityName&appid=$apiKey&units=metric');

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

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

bbmckpt7

bbmckpt71#

只需添加括号,使其成为非静态的。具体如下:

var weatherData = await WeatherModel().getLocationWeather();

字符串

s4n0splo

s4n0splo2#

若要作为静态方法访问,需要将方法设为静态

static Future<dynamic> getLocationWeather() async {
 /// if this function depends on others , those also neeeded to be static as well.

字符串
现在你可以用

var weatherData = await WeatherModel.getLocationWeather();


或者使用WeatherModel().getLocationWeather();将在每次调用时创建一个新示例。

相关问题