Flutter ENVied package build runner error

581 views Asked by At

The problem I am facing is with ENVied package for flutter. I am trying to save my api keys in environment variables.

I followed these steps.

  1. Installed these three packages
$ flutter pub add envied
$ flutter pub add --dev envied_generator
$ flutter pub add --dev build_runner
  1. I created .env file and saved my api key in it. File Structure

  2. After this, I created the env.dart file with the following code:

import 'package:envied/envied.dart';

part 'env.g.dart';

@Envied(path: '.env')
abstract class Env {
  @EnviedField(varName: 'TEST_KEY')
  static final String apiKey = _Env.apiKey;
}

  1. Then I ran the build runner command. dart run build_runner build

After this command I faced the error saying Envied requires types to be explicitly declared. 'apiKey' does not declare a type.

  1. So I made changes in my code and declared a type of String and ran the command again.

Now I faced another build runner error stating Environment variable not found for field '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. I checked out the possible issue here but still none of those responses helped me with this issue.

1

There are 1 answers

0
Dhiraj Mishra On
import 'package:envied/envied.dart';

part 'env.g.dart';

@Envied(path: '.env') //give full path here with name like secret.env instead of only extension
abstract class Env {
@EnviedField(varName: 'varNameHere')
static String varNameHere = _Env.varNameHere;
}

the variables name should be the same at all three places. Here in your case your varName is 'TEST_KEY', and variable storing name is apikey. so replace all three places with same name as in example above and run command:

dart run build_runner build --delete-conflicting-outputs

this will generate all files necessary & follow the pub.dev envied instructions. This article may be helpful securing API keys in flutter