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

10,661

Solution 1

The new version of .env library has this feature:

flutter_dotenv: ^3.1.0


BAR=bar

FOOBAR=$FOO$BAR

ESCAPED_DOLLAR_SIGN='$1000'

Solution 2

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.

Share:
10,661
MHDEZ
Author by

MHDEZ

Updated on June 09, 2022

Comments

  • MHDEZ
    MHDEZ almost 2 years

    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

  • MHDEZ
    MHDEZ about 4 years
    I want to use them inside the file. Like: getData = host:port/myData
  • Eduardo Vital
    Eduardo Vital about 4 years
    This can be accomplished by creating a dart file with plenty of constants that are compound by the env variables. Like: String getData = `${DotEnv().env['HOST']}:${DotEnv().env['PORT']}/data`;. If you could provide a case where this does not achieve its goals, please include it in your question.
  • user3808307
    user3808307 over 3 years
    The project is looking for the .env file inside the assets folder! IS this normal? how can i change it so it tries to use a .env at the root?
  • Llama
    Llama about 3 years
    you need to set DotEnv as an import variable like this if you want this to work w these instructions: import 'package:flutter_dotenv/flutter_dotenv.dart' as DotEnv; This explanation is missing this information.