如何在Flutter中使用Provider Package创建全局变量?

ZKJ*_*ZKJ 3 dart flutter

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

大致上我正在尝试做的事情:

//inside main.dart
int anInteger = 0;

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

//inside another file
changeInteger(9);
Run Code Online (Sandbox Code Playgroud)

Mob*_*ina 7

您可以在一个新文件中新建一个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
  }
}
Run Code Online (Sandbox Code Playgroud)

文件:main.dart

import 'globals.dart';
...
FlatButton(
  onPressed: () {
     Globals.changeInteger(9);
  },
...
Run Code Online (Sandbox Code Playgroud)