ZKJ
ZKJ

Reputation: 167

How to create global variables using Provider Package in Flutter?

My Flutter app needs a global variable that is not displayed(so no UI changes) but it needs to run a function everytime it is changed. I've been looking through tutorials etc. but they all seem to be for much more complicated uses than what I need and I'd prefer to use the simplest approach that is still considered "good practice".

Roughly what I am trying to do:

//inside main.dart
int anInteger = 0;

int changeInteger (int i) = {
  anInteger = i;
  callThisFunction();
}

//inside another file
changeInteger(9);

Upvotes: 3

Views: 6232

Answers (1)

Mobina
Mobina

Reputation: 7109

You can make a new Class in a new file to store the global variable and its related methods. Whenever you want to use this variable, you need to import this file. The global variable and its related methods need to be static. Pay attention to the callThisFunction that you mentioned in your question, it needs to be static as well (since it would be called in a static context). e.g.

file: globals.dart

class Globals {
  static var anInteger = 0;
  static printInteger() {
    print(anInteger);
  }
  static changeInteger(int a) {
    anInteger = a;
    printInteger(); // this can be replaced with any static method
  }
}

file: main.dart

import 'globals.dart';
...
FlatButton(
  onPressed: () {
     Globals.changeInteger(9);
  },
...

Upvotes: 7

Related Questions