Panashe
Panashe

Reputation: 139

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

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

Upvotes: 2

Views: 4613

Answers (2)

Furkan
Furkan

Reputation: 306

Try this

  class _InvestPageState extends State<InvestPage> {
      late Future<Markets> _Markets;
    
      @override
      void initState() {
        Services().getMarkets().then((value) {
           _Markets = value;
        });
        super.initState();
      }
   }

You are used future return type, so you cannot be access through instance.

Upvotes: -1

Sahil Hariyani
Sahil Hariyani

Reputation: 1178

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

Change this

_Markets = Services().getMarkets();

to

_Markets = Services.getMarkets();

Upvotes: 3

Related Questions