flutter_dotenv icon indicating copy to clipboard operation
flutter_dotenv copied to clipboard

Rename dotenv.testLoad to dotenv.loadString

Open lukepighetti opened this issue 2 years ago • 1 comments

I think we can provide a little more clarity on loading env files from a string by changing the name of this method so it's clear that this is useful outside of test scenarios

Why would you want to load an environment variable from a string in a production app?

Ideally .env files are not baked into the app package assets because they are easy to get access to. We can provide a little bit of obfuscation by loading them into the binary as a compile time string.

ENVIRONMENT=DEVELOPMENT
FASTAPI_KEY=my_public_key
FASTAPI_HOST=localhost
FASTAPI_PORT=8000
// .vscode/launch.json
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "app",
      "request": "launch",
      "type": "dart",
      "args": ["--dart-define=ENV=$(cat .env | base64)"] // pull the .env file from filesystem and pipe it to const string via base64
    }
  ]
}

// config.dart
void main() {
  const b64env = String.fromEnvironment('ENV'); // load the base64 encoded .env file
  dotenv.testLoad(fileInput: b64env.fromBase64()); // load it into dotenv, << this is where I think we can add some clarity
  config = Config();
}

class Config {
  final environment = Environment.values.byName(dotenv.get('ENVIRONMENT'));
  final fastApiPort = dotenv.getInt('FASTAPI_PORT').assertPortNumber();
  final fastApiHost = dotenv.get('FASTAPI_HOST').assertNotEmpty();
  final fastApiKey = dotenv.get('FASTAPI_KEY').assertNotEmpty();
}

extension StringExtensions on String {
  String fromBase64() {
    return utf8.decode(base64.decode(this));
  }
}

lukepighetti avatar May 05 '23 15:05 lukepighetti

If we wanted to get even more sugary, we could add dotenv.loadBase64String()

lukepighetti avatar May 05 '23 15:05 lukepighetti