dart - 在 Flutter 中设置环境变量

例如,为 API 构建客户端,例如 Twitch。

在 Dart CLI 二进制文件中,我可以使用通用环境变量或 Dart 定义变量。例如,将两者都用作后备:

main() {
  String clientId = 
      // dart -dCLIENT_ID='abc bin/example.dart
      // This is considered "compiled-into" the application.
      const String.fromEnvironment('CLIENT_ID') ??

      // CLIENT_ID='abc' dart bin/example.dart
      // This is considered a runtime flag.
      Platform.environment['CLIENT_ID'];

  // Use clientId.
}

Flutter 是否有办法设置其中一个/两个,特别是...

  • 在开发期间
  • 运送到产品时

一旦我弄清楚如何帮助一些文档,我很高兴:)

最佳答案

从 Flutter 1.17 开始,您可以根据需要定义编译时变量。

为此,只需在 flutter runflutter build

期间使用 --dart-define 参数

如果需要传递多个键值对,只需定义--dart-define多次即可:

flutter run --dart-define=SOME_VAR=SOME_VALUE --dart-define=OTHER_VAR=OTHER_VALUE

然后,您可以在代码中的任何位置使用它们,例如:

const SOME_VAR = String.fromEnvironment('SOME_VAR', defaultValue: 'SOME_DEFAULT_VALUE');
const OTHER_VAR = String.fromEnvironment('OTHER_VAR', defaultValue: 'OTHER_DEFAULT_VALUE');

此外,它们也可以在原生层中使用。

Here is an article that explains more.

https://stackoverflow.com/questions/44250184/

相关文章:

dart - Flutter:如何制作随机颜色生成器背景

flutter - 如何在 AppBar 中用图像替换标题

dart - Flutter ListView 项目点击监听器

dart - Flutter BLoC 模式 - 如何在流事件后导航到另一个屏幕?

dart - 如何使用 image.file 加载图像

dart - 如何在 flutter 中实现推送通知

android - 如何在 TextFormField 中显示/隐藏密码?

android - flutter : How can I add divider between

flutter - 如何更改 FloatingActionButton 的大小?

android - Flutter 上的小部件的 onResume() 和 onPause()