skip to Main Content

I am getting this error

Instance member can’t be accessed using static access

and I can’t locate where as I have data related to the error in another class. Am new to Dart Flutter and still learning, so it all isn’t making sense to me much.

Code where am getting this error is at .getLocationWeather():

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

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

Below is the class’ code where getLlocationWeather() is located.

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

2

Answers


  1. Simply add the brackets around to make it non-static. As following:

    var weatherData = await WeatherModel().getLocationWeather();
    
    Login or Signup to reply.
  2. To access as static method, you need the make the method as static

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

    Now you can use

    var weatherData = await WeatherModel.getLocationWeather();
    

    Or using WeatherModel().getLocationWeather(); will create a new instance every time you call it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search