Muhammad Faisal
Muhammad Faisal

Reputation: 127

Instance members can't be accessed from a static method Flutter

Im trying to call playRefreshBar in my code , but i get warning like this

Instance members can't be accessed from a static method

this is code in my static

  static List<charts.Series<Spending, String>> createRandomData(){
    Timer(Duration(milliseconds:1000),(){
      playRefreshBar();
    });
  }

code playRefreshBar

  void playRefreshBar() {
    timer = Timer.periodic(Duration(milliseconds: refreshTime), (Timer t){
      final random = new Random();

      final data = [
        new Spending('2013', random.nextInt(1000000)),
        new Spending('2014', random.nextInt(1000000)),
        new Spending('2015', random.nextInt(1000000)),
        new Spending('2016', random.nextInt(1000000)),
        new Spending('2017', random.nextInt(1000000)),
        new Spending('2018', random.nextInt(1000000)),
        new Spending('2019', random.nextInt(1000000)),
      ];

      return[
        new charts.Series(id: 'Spending',
            data: data,
            domainFn: (Spending sp, _) => sp.year,
            measureFn: (Spending sp , _) => sp.spending,
            labelAccessorFn: (Spending sp, _) => '${sp.year}: \$${sp.spending}'
        )
      ];
    });
  }

Upvotes: 6

Views: 26517

Answers (1)

aqwert
aqwert

Reputation: 10789

The reason a static method cannot call an instance method is because the instance that you want to use is not included.

Since you can create any number of instance objects that the instance method will be used on, the static (single global method) needs to know which one you are referring to.

static List<charts.Series<Spending, String>> createRandomData(){
 Timer(Duration(milliseconds:1000),(){
   instance.playRefreshBar();
 });
}

where instance is

final instance = new ClassThatHasPlayRefreshBar();

Or, you will need to make the instance method also static

static void playRefreshBar()

Upvotes: 12

Related Questions