Home > database >  The static method can't be acessed through an instance. Try using the class 'services'
The static method can't be acessed through an instance. Try using the class 'services'

Time:03-23

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

CodePudding user response:

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

Change this

_Markets = Services().getMarkets();

to

_Markets = Services.getMarkets();

CodePudding user response:

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.

  • Related