Ad

The Static Method Can't Be Acessed Through An Instance. Try Using The Class 'services' To Acess The Method

- 1 answer

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

Answer

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

Change this

_Markets = Services().getMarkets();

to

_Markets = Services.getMarkets();
Ad
source: stackoverflow.com
Ad