How do I define a variable inside an .env file in Flutter?

Viewed 15169

I am using this library. I want to define a variable for host and port in `.env file in Flutter, and I want to use them inside the file.

Like:

getData= host:port/myData

2 Answers

You can do that by inserting in the .env file:

HOST=localhost
PORT=3000

Add the .env file in the assets section of the pubspec.yaml:

assets:
  - .env

Then, you can change the main function in the main.dart to load the .env file:

Future main() async {
  await DotEnv().load('.env');
  runApp(MyApp());
}

After that, you can get the HOST and PORT anywhere with:

DotEnv().env['PORT'];
DotEnv().env['HOST'];

All these instructions are in the README of the library: https://pub.dev/packages/flutter_dotenv#-readme-tab-

Edit after update of the question: I took a look at the DotEnv library source code and they did not implement this feature that you need. You can create an issue to request this if you really need it or you can use a workaround like create a Constants class that compounds these environment variables in the way you need it.

The new version of .env library has this feature:

flutter_dotenv: ^3.1.0


BAR=bar

FOOBAR=$FOO$BAR

ESCAPED_DOLLAR_SIGN='$1000'
Related