Search code examples
flutterenvironment-variablesobfuscationapi-key

Problem setting up ENVIED package in Flutter to hide API key


I want to use an API key in my flutter app, and have read that the envied package is a good tool to keep the API key hidden.

The issue is I can't get this working. This is what I've done:

  1. Installed the 3 packages:
$ flutter pub add envied
$ flutter pub add --dev envied_generator
$ flutter pub add --dev build_runner
  1. Created a file in the root folder named .env to store the key
API_KEY=1234567890
  1. Created a class in lib/env/env.dart
import 'package:envied/envied.dart';

part 'env.g.dart';

@Envied(path: '.env')
abstract class Env {
  @EnviedField(varName: 'API_KEY')
  static final apiKey = _Env.apiKey;
}
  1. Then run:
flutter pub run build_runner build

And then I get this error:

[SEVERE] envied_generator:envied on lib/env/env.dart:

Envied can only handle types such as `int`, `double`, `num`, `bool` and `String`. Type `InvalidType` is not one of them.
  ╷
9 │   static final apiKey = _Env.apiKey;

And a env.g.dart file is not generated.

I have tried a few times and from what I can tell I am following the set up on pub.dev exactly, so not sure how to fix it.


Solution

  • For the obfuscator to work, you need to specify a variable type. Example:

    static final String apiKey = _Env.apiKey;