人间工作P 人间工作P
主站 (opens new window)
首页
  • Bukkit开发教程
投喂
关于
  • 分类
  • 标签
  • 时间线
  • 友情链接

人间工作P

我每天都好困… 最近在学习和进行 VOCALOID 创作
主站 (opens new window)
首页
  • Bukkit开发教程
投喂
关于
  • 分类
  • 标签
  • 时间线
  • 友情链接
  • 在构建/运行 Flutter 应用时添加环境变量,作出差异化调整

    • 使用案例
    MrXiaoM
    2026-03-30
    开发
    目录

    在构建/运行 Flutter 应用时添加环境变量,作出差异化调整

    例如在 Vercel 环境下使用不同的后端地址

    通常在做前端开发时可能会存在多个环境,如果换一个环境就改一次代码中的参数太麻烦了,获取环境变量可能是一个更好的方法。

    构建/运行时,只需要添加以下参数即可添加环境变量

    flutter build (...) --dart-define=键=值
    flutter run (...) --dart-define=键=值
    
    1
    2

    需要获取环境变量时,只需要使用 fromEnvironment 方法就可以了

    const IS_VERCEL = bool.fromEnvironment('VERCEL', defaultValue: false);
    
    1

    # 使用案例

    // ignore_for_file: constant_identifier_names
    
    class BuildConstants {
      static const API_HOST = bool.fromEnvironment('LOCAL_TEST', defaultValue: false)
          ? "内网测试地址"
          : "公网生产地址";
      static const IN_VERCEL = bool.fromEnvironment('VERCEL', defaultValue: false);
    
      static String getWebApiHost() {
        if (IN_VERCEL) {
          return '/api'; // Vercel 重写 /api 到公网生产地址
        } else {
          return API_HOST;
        }
      }
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16

    使用以下命令运行测试网页端,使用内网测试地址。

    flutter run -d web-server --dart-define=LOCAL_TEST=true
    
    1

    使用以下命令构建网页端,使用公网生产地址,可作为静态站点部署到 nginx 等服务器软件上。

    flutter build web --release --no-web-resources-cdn
    
    1

    部署到 Vercel,使用以下命令来构建,使用 /api 作为后端地址,在 Vercel 配置文件增加重写转发。

    flutter build web --release --no-web-resources-cdn --dart-define=VERCEL=true
    
    1

    把这些命令写成脚本,需要什么就运行什么。

    编辑 (opens new window)
    #前端#Flutter#Google
    上次更新: 2026/03/30, 08:57:51
    最近更新
    01
    白嫖老黄的 NVIDIA AI 模型
    03-20
    02
    临时修改 MMOItems 的数值属性,实现不同玩家不同属性功能
    03-13
    03
    在 Windows 上安装 WSL2 + Docker + Docker-Compose
    03-11
    更多文章>
    Theme fork from Vdoing | Copyright © 2018-2026 人间工作P | 友情链接
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式