dotenv: Unhandled Exception: Instance of 'FileNotFoundError'

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await dotenv.load(fileName: "./env");
  var documentsDirectory =
      await path_provider.getApplicationDocumentsDirectory();

  Hive.init(documentsDirectory.path);
  Hive.registerAdapter(UserDataModelAdapter());
  Hive.registerAdapter(TaskHiveModelAdapter());

  runApp(const MyApp());
}

My file directory:
enter image description here

Error on build:

No file or variants found for asset: .env.
Error detected in pubspec.yaml:

Target debug_android_application failed: Exception: Failed to bundle asset files.


FAILURE: Build failed with an exception.

I have the .env set up in pubspec.yaml like so:

  • assets:
    • .env

How can Flutter don’t find the .env file on startup?

>Solution :

1.The relative path might be causing issues, you can try using an absolute path to the .env file.

await dotenv.load(fileName: '/full/path/to/your/project/.env');

OR

await dotenv.load(fileName: 'env');

2.Do check your pubspec.yaml file to ensure that the .env file is present in the asset.

 flutter:
  assets:
    - .env

3.Make sure the File Permissions:

Make sure that you have read access to the .env file. 

Leave a Reply