Securing sensitive data in Flutter
In this article you will learn how you can store securely sensitive data like api keys, passwords etc in flutter using .env file and the envied package (https://pub.dev/packages/envied) which will help you access enviroment variables secure and easy.
Let’s jump to the coding part.
Step 1: Import the following dependencies
dependencies:
envied: ^0.3.0+3 //This is the library providing the annotations
dev_dependencies:
build_runner: ^2.4.6 // This is the tool used to run the code generator
envied_generator: ^0.3.0+3 //This is used to generate the required files(code)
Step 2: Create the .env file and add it to .gitignore
Next at the root level of the project create .env file. (.env will be the actual file name). In which you will add the sensitive data as KEY=VALUE and the IDE will promt option to install .env plugin.
Step 3: Create the Env class file and the AppEnv file and add them to .gitignore
Then under the lib file you need to create the env.dart class file in which the values of .env file will get accessed with the use of Envied annotations.
import 'package:envied/envied.dart';
part 'env.g.dart';
@Envied(path: '.env')
final class Env {
//varName is the key we used in the .env file(in our example is the API_KEY)
@EnviedField(varName: 'API_KEY')
static const key1 = _Env.key1;
}
Step 4: Generate code using the Build Runner
The last step before you can access sensitive data is to generate the Env.g.dart file which includes the require code needed to access the data. To achive this simply use the following command in the terminal.
flutter pub run build_runner build
or
flutter pub run build_runner build --delete-conflicting-outputs(This if auto
generated file already exists)
NOTE: Please note that the above commants are now depricated. The alternative commands are
dart run build_runner build
or
dart run build_runner build --delete-conflicting-outputs
Step 5: Access sensitive data
Access sensitive data by accessing the Env variable.
import 'envie_files/Env.dart';
String apiKey = Env.apiKey;
Tips: You can use @EnviedField(obfuscate: true) as an extra step of security.
I hope you found this article helpful. You can also find the example project on my GitHub profile.
GitHub Example Project: https://github.com/r1n1os/Secure-Sensitive-Data-Example
References:
- https://pub.dev/packages/envied