The static method can't be acessed through an instance. Try using the class 'services' to acess the method

Issue

Hi can anyone help me with this problem I’m facing when calling API’s in flutter, this is the code for fetching the data

class _InvestPageState extends State<InvestPage> {
  late Future<Markets> _Markets;

  @override
  void initState() {
     _Markets = Services().getMarkets(); //error here
    super.initState();
  }

This is the code in my API manager file

import 'package:gem_portal_new/Login/newsinfo.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

class Services {
  static const String url = 'https://ctrade.co.zw/mobileapi/MarketWatch';

  static Future<List<Markets>> getMarkets() async {
    try {
      final response = await http.get(Uri.parse(url));
      if (200 == response.statusCode) {
        final List<Markets> markets = marketsFromJson(response.body);
        return markets;
      } else {
        return <Markets>[];
      }
    } catch (e) {
      return <Markets>[]; 
    }
  }
}

Solution

You are trying to access a static method using a object instance,

Change this

_Markets = Services().getMarkets();

to

_Markets = Services.getMarkets();

Answered By – Sahil Hariyani

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *