在測試和自動整合 Flutter app 時,常需要替它切換不同環境去重現問題和自動量測運作效率,像是 http request 到不同的後端服務環境,以下這篇文章介紹如何使用在 flutter 程式碼易於切換不同環境的設定值。
在 pubspec.yml 檔案加入套件: flutter_dotenv: ^2.0.1
假設你有以下檔案: main_development.dart
, main_production.dart
, routes_development.dart
, routes_production.dart
, pubspec.yml
main_development.dart :
import './routes_development.dart';
void main() {
new Routes();
}
routes_development.dart
import 'package:flutter/material.dart';
class Routes {
final routes = <String, WidgetBuilder> {
.... // your app routing1
.... // your app routing2
};
Routes() {
initEnvironment().then( (_) {
runApp(new MaterialApp(
routes: routes,
));
});
}
initEnvironment() async {
await DotEnv().load('.env.dev');
}
}
main_production.dart
:
import './routes_production.dart';
void main() {
new Routes();
}
routes_production.dart
import 'package:flutter/material.dart';
class Routes {
final routes = <String, WidgetBuilder> {
.... // your app routing1
.... // your app routing2
};
Routes() {
initEnvironment().then( (_) {
runApp(new MaterialApp(
routes: routes,
));
});
}
initEnvironment() async {
await DotEnv().load('.env.prod');
}
}
pubspec.yml
在內容 assets 區塊加上你要載入的環境參數設定檔:
assets:
- ./env.production # 正式環境
- ./env.development # 開發環境
環境參數設定檔請設定跟 pubspec.yml 的相對檔案路徑(relative file path)。
命令列編譯時可使用以下指令,切換編譯環境設定值:
flutter build apk -t lib/main_development.dart
flutter build apk -t lib/main\_production.dart
若使用 vscode IDE 介面,請在專案底下的 .vscode/launch.json
檔案內,使用以下設定切換編譯環境設定值:
{
"version": "0.2.0",
"configurations": [
{
"name": "Flutter-production",
"type": "dart",
"request": "launch",
"program": "lib/main_production.dart",
},
{
"name": "Flutter-development",
"type": "dart",
"request": "launch",
"program": "lib/main_development.dart",
}
]
}
參考資料:
1. https://github.com/flutter/flutter/issues/18377
2. https://pub.dev/packages/flutter_dotenv