如何为 Flutter 应用程序创建环境变量

我们为什么需要环境变量?

主要用于存储高级机密数据,如果泄露可能会危及您产品的安全性。这些变量本地存储在每个用户的本地系统中,不应该签入存储库。每个用户都有这些变量的副本。

配置

  • 在根项目中创建一个名为 .env 的文件夹(文件夹名称由您选择)

  • .gitignore 中添加 .env 文件夹路径为 .env/

  • .env 文件夹中添加环境文件,如 dev.jsonstaging.jsonprod.jsontesting.json 或任何你想创建的环境。

步骤

通过 CLI 设置环境变量

  • 运行命令: flutter run --dart-define-from-file=.env/dev.json

设置 VSCode 运行环境变量

  • .vscode/ 文件夹中创建 launch.json 文件,从而创建启动配置。

  • 为每个环境创建配置,并在 toolArgs 字段中添加选项 --dart-define-from-file=.env/dev.json,如下所示:

json 复制代码
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "mobile_app dev",
            "request": "launch",
            "type": "dart",
            "toolArgs": [
                "--dart-define-from-file=.env/dev.json"
            ]
        },
        {
            "name": "mobile_app staging",
            "request": "launch",
            "type": "dart",
            "toolArgs": [
                "--dart-define-from-file=.env/staging.json"
            ]
        },
        {
            "name": "mobile_app prod",
            "request": "launch",
            "type": "dart",
            "toolArgs": [
                "--dart-define-from-file=.env/prod.json"
            ]
        },
        {
            "name": "mobile_app testing",
            "request": "launch",
            "type": "dart",
            "toolArgs": [
                "--dart-define-from-file=.env/testing.json"
            ]
        }
    ]
}

设置从Android Studio运行的环境变量

  • 单击edit configurations打开配置
  • 单击左上角的 + 并从下拉列表中选择 flutter 以添加多个 flutter 配置
  • 在"Dart entrypoint"中,将值设置为main.dart文件的路径

  • 在"Additional run args"字段中添加 --dart-define-from-file=.env/dev.json

  • 重复上述第 2、3 和 4 步,为多个环境创建多个配置

使用环境变量

要使用环境变量,请使用 String.fromEnvironment('clientId');

您可以创建一个返回静态环境变量的类(或者您也可以用自己的方法来实现),它看起来像这样

dart 复制代码
class Environment {
  static const String env = String.fromEnvironment('env');
  static const String clientId = String.fromEnvironment('clientId');
  static const String clientSecret = String.fromEnvironment('clientSecret');
  static const String callbackUrl = String.fromEnvironment('callbackUrl');
}

并在代码中作为 Environment.clientId 使用

您的机密数据现在安全了!🎉


原文:blog.nonstopio.com/how-to-crea...

相关推荐
用户2181697049308 小时前
Flutter ClipPath
flutter
用户21816970493011 小时前
Flutter 折叠组件 ExpansionTile ExpansionPanelList
flutter
不羁的木木1 天前
给鸿蒙 App 增加用系统应用打开文件的能力 —— open_app_file 的鸿蒙使用指南
flutter·harmonyos
HouWan1 天前
Flutter: MediaQuery.of(context) 为什么可能拖慢页面?
android·flutter·ios
西西学代码2 天前
flutter---井字游戏
flutter
tushanxing2 天前
Day 2: 容器与单子布局基础
flutter
程序员老刘2 天前
跨平台开发地图 | 2026年9月
flutter·客户端
HouWan3 天前
Flutter iOS UISceneDelegate 迁移指南:理清新的 Scene 生命周期
flutter·ios·app
技术任我行XTing3 天前
【DFX系列】Flutter 鸿蒙应用外接纹理介绍及问题定位
flutter·harmonyos