When building a Flutter app, managing environment variables securely is crucial. Hardcoding API keys, such as a Supabase key, in your source code can lead to security risks. Instead, dart-define allows you to pass environment variables dynamically at runtime. In this blog, we will explore how to use dart-define
to manage environment variables efficiently in Flutter.
Why Use dart-define?
- Security: Keeps sensitive data out of your source code.
- Flexibility: Easily switch between different environments (development, staging, production).
- No Additional Dependencies: Works natively with Flutter.
How to Use dart-define in Flutter
1. Passing Environment Variables with dart-define
When running your Flutter app, pass the variable using the --dart-define
flag:
flutter run --dart-define=SUPABASE_KEY=your-secret-key
For release builds:
flutter build apk --dart-define=SUPABASE_KEY=your-secret-key
2. Accessing Environment Variables in Dart
Modify your Dart code to retrieve the value using String.fromEnvironment
:
const supabaseUrl = 'https://your-supabase-url.supabase.co';
const supabaseKey = String.fromEnvironment('SUPABASE_KEY', defaultValue: '');
Now, supabaseKey
will only be set when passed via --dart-define
, preventing it from being hardcoded in your source code.
3. Automating dart-define in VS Code and Android Studio
If you don’t want to type flutter run --dart-define
every time, you can configure it in your development environment.
In VS Code
- Open
.vscode/launch.json
(create it if missing). - Add the
--dart-define
flag underargs
:{ "configurations": [ { "name": "Flutter", "request": "launch", "type": "dart", "program": "lib/main.dart", "args": ["--dart-define=SUPABASE_KEY=your-secret-key"] } ] }
In Android Studio
- Go to Run > Edit Configurations.
- Find Additional Run Args.
- Add:
--dart-define=SUPABASE_KEY=your-secret-key
Now, every time you press Run, your Supabase key will be injected dynamically!
4. Using dart-define in CI/CD Pipelines
If you’re deploying your Flutter app using a CI/CD pipeline, you can pass environment variables dynamically:
GitHub Actions Example
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout Code
uses: actions/checkout@v2
- name: Setup Flutter
uses: subosito/flutter-action@v2
- name: Build APK
run: flutter build apk --dart-define=SUPABASE_KEY=${{ secrets.SUPABASE_KEY }}
By storing the SUPABASE_KEY
in GitHub Secrets, your API key remains secure.
Conclusion
Using dart-define
in Flutter is the best way to manage environment variables securely. It ensures your sensitive information is not exposed in your source code, enhances flexibility, and integrates seamlessly into development and CI/CD workflows. Whether you’re using VS Code, Android Studio, or CI/CD pipelines, dart-define
helps keep your app safe and efficient.
Start using dart-define
today to improve your Flutter app security and flexibility! 🚀