An example Flutter project demonstrating how to securely pass environment variables using --dart-define-from-file.
-
Ensure Flutter is Updated
Upgrade Flutter if needed:
flutter upgrade
-
Create Environment Files
-
Development (
env.dev.json) and Production (env.prod.json) Files:{ "API_URL": "https://your-api.example.com", "API_KEY": "your_api_key" }
Note: Replace placeholder values with your actual API URLs and keys.
-
-
Add Environment Files to
.gitignoreenv.dev.json env.prod.json
-
Update
lib/main.dartUse
String.fromEnvironmentto access the variables:static const apiUrl = String.fromEnvironment('API_URL', defaultValue: 'Not Found'); static const apiKey = String.fromEnvironment('API_KEY', defaultValue: 'Not Found');
-
Run the App in Development Mode:
flutter run --dart-define-from-file=env.dev.json
-
Build the App for Production:
flutter build apk --release --dart-define-from-file=env.prod.json
- Store environment variables securely in your CI/CD platform and generate environment files at build time.
Feel free to reach out if you have any questions!