我的Flutter应用程序需要一个不会显示的全局变量(因此用户界面不会更改),但是每次更改时都需要运行一个函数。我一直在浏览教程等,但是它们似乎都比我需要的要复杂得多,我更喜欢使用仍然被认为是“良好实践”的最简单方法。
大概我想做的是:

//inside main.dart
int anInteger = 0;

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

//inside another file
changeInteger(9);

最佳答案

您可以在新文件中创建一个新的Class来存储全局变量及其相关方法。每当您要使用此变量时,都需要导入此文件。全局变量及其相关方法需要为static。请注意您在问题中提到的callThisFunction,它也必须是静态的(因为它将在静态上下文中调用)。例如
文件: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
  }
}
文件:main.dart
import 'globals.dart';
...
FlatButton(
  onPressed: () {
     Globals.changeInteger(9);
  },
...

10-08 10:52