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);
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);
},
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With