How to add environment variable to my flutter custom package properly?

105 Views Asked by At

I have an App and a custom package, when i try to use my package's environment variable it can not be found. this is my package pubspec:

assets: 
 - 2.env

and this is for my App:

assets: 
 - 1.env

this is my package:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  await dotenv.load(fileName: '2.env');
  print(dotenv.env['ENV_TYPE']!);
}

and this is how I use my package in my app:

import 'package:my_package/package.dart' as pack;
...
      CupertinoButton(
              child: const Text("Run Package"),
              onPressed: () {
                pack.main();
              },
            ),

When I use 1.env(main App pubspec file) the package works fine(even though I have not added it in my package pubspec) and prints the value, however, when i try the 2.env which is the file added in package pubspec I get (FileNotFoundError). First I believed that it has something to do with the path in the package pubspec so i also tryed something like this - packages/my_package/2.env but i belive this is not the issue as the package gets up and running without a problem so I think await dotenv.load(fileName: '2.env'); causes the problem. Why my custom package can't find it's own dependency (2.env) whereas it is fine with the app file(1.env) which is not even included in the package pubspec.

1

There are 1 best solutions below

0
FaBotch On

To manage env, I use flutter_config

import 'package:flutter_config/flutter_config.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized(); // Required by FlutterConfig
  await FlutterConfig.loadEnvVariables();

  runApp(MyApp());
}

in android/app/build.gradle (assuming you have flavor "staging" and "production")

project.ext.envConfigFiles = [staging: "env/.1.env",
    production: "env/.2.env"]


apply from: project(':flutter_config').projectDir.getPath() + "/dotenv.gradle"

when build, it will take 1.env or 2.env depends on the flavor.

then, you can use in your code

import 'package:flutter_config/flutter_config.dart';

FlutterConfig.get('ENV_TYPE')

on iOS, for each Scheme

enter image description here

It will create a .envfile at build (in iOS folder) and will replace the content with 1.env or 2.env