- Dart Cookbook
- Ivo Balbaert
- 334字
- 2021-08-05 17:42:49
Using different settings in the checked and production modes
Often the development and deployment environments are different. For example, the app has to connect to a different database or a different mail server in either environment to use a mocked service in development and the real service in production, or something like that. How can we use different setups in both modes, or achieve a kind of precompiler directive-like functionality?
How to do it...
Perform the following steps to use different settings:
- Add a transformers section to
pubspec.yaml
with an environment line that specifies a map of the settings, names and values, as follows (see the code indev_prod_settings
):transformers: # or dev_transformers - $dart2js: environment: {PROD: "true", DB: "MongoPROD"}
- You can, for example, get the value of the DB setting from
const String.fromEnvironment('DB')
, as you can see in the following code:import 'dart:html'; void main() { print('PROD: ${const String.fromEnvironment('PROD')}'); bool prod = const String.fromEnvironment('PROD') == 'true'; if (prod) { // do production things window.alert("I am in Production!"); connectDB(const String.fromEnvironment('DB')); } else { // do developer / test things } log('In production, I do not exist'); } log(String msg) { if (const String.fromEnvironment('DEBUG') != null) { print('debug: $msg'); } } connectDB(String con) { // open a database connection }
- When run in the Dart VM (and in the checked mode), the console gives
PROD: null
as an output when run as JavaScript in Chrome; an alert dialog appears and the console in the Developer Tools shows PROD: true.
How it works...
The import initializer option requires a manual code change in order to switch the environment. The transformers option uses environment declarations that are provided by the surrounding system compiling or running the Dart program. This is better because it only requires changing the configuration file pubspec.yaml
. However, at the moment, it is only defined for dart2js, in order to deploy to JavaScript.
Make sure that the environment is indented; otherwise, you may get the error "transformers" must have a single key: the transformer identifier
.
- 物聯網智慧安監技術
- 面向物聯網的CC2530與傳感器應用開發
- EDA技術與VHDL編程
- 網管員典藏書架:網絡管理與運維實戰寶典
- TCP/IP入門經典(第5版)
- 數字調制解調技術的MATLAB與FPGA實現:Altera/Verilog版(第2版)
- Learning Swift(Second Edition)
- Mastering Dart
- 通信十年:擁抱互聯網
- 6G無線網絡空口關鍵技術
- Hands-On Bitcoin Programming with Python
- 算力網絡:云網融合2.0時代的網絡架構與關鍵技術
- Cisco無線局域網配置基礎
- 智慧的物聯網:感知中國和世界的技術
- 網絡基本通信約束下的系統性能極限分析與設計