dotenv: Unhandled Exception: Instance of 'FileNotFoundError'

597 Views Asked by At
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?

1

There are 1 best solutions below

5
gretal On BEST ANSWER
  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');
  1. Do check your pubspec.yaml file to ensure that the .env file is present in the assets.
flutter:
  assets:
    - .env
  1. Make sure the File Permissions:
    Make sure that you have read access to the .env file.